How do I remove repeated spaces in a string?

前端 未结 7 1858
悲哀的现实
悲哀的现实 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:45

    Use a regular expression to match repeating whitespace (\s+) and replace it by a space.

    "foo    bar  foobar".gsub(/\s+/, ' ')
    => "foo bar foobar"
    

    This matches every whitespace, as you only want to replace spaces, use / +/ instead of /\s+/.

    "foo    bar  \nfoobar".gsub(/ +/, ' ')
    => "foo bar \nfoobar"
    

提交回复
热议问题