Regex to replace multiple spaces with a single space

后端 未结 23 2717
北恋
北恋 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:07

    A more robust method: This takes care of also removing the initial and trailing spaces, if they exist. Eg:

    // NOTE the possible initial and trailing spaces
    var str = "  The dog      has a long   tail, and it     is RED!  "
    
    str = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
    
    // str -> "The dog has a long tail, and it is RED !"
    

    Your example didn't have those spaces but they are a very common scenario too, and the accepted answer was only trimming those into single spaces, like: " The ... RED! ", which is not what you will typically need.

提交回复
热议问题