Regex to replace multiple spaces with a single space

后端 未结 23 2602
北恋
北恋 2020-11-22 10:00

Given a string like:

\"The dog      has a long   tail, and it     is RED!\"

What kind of jQuery or JavaScript magic can be used to keep spaces to only o

23条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 10:12

    Given that you also want to cover tabs, newlines, etc, just replace \s\s+ with ' ':

    string = string.replace(/\s\s+/g, ' ');
    

    If you really want to cover only spaces (and thus not tabs, newlines, etc), do so:

    string = string.replace(/  +/g, ' ');
    

提交回复
热议问题