How do I remove repeated spaces in a string?

前端 未结 7 1844
悲哀的现实
悲哀的现实 2020-12-29 20:05

I have a string:

\"foo (2 spaces) bar (3 spaces) baaar (6 spaces) fooo\"

How do I remove repetitious spaces in it so there shou

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-29 20:40

    Just use gsub and regexp. For example:

    str = "foo  bar   bar      baaar"
    str.gsub(/\s+/, " ")
    

    will return new string or you can modify str directly using gsub!.

    BTW. Regexp are very useful - there are plenty resources in the internet, for testing your own regexpes try rubular.com for example.

提交回复
热议问题