Regex to replace multiple spaces with a single space

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

    This is one solution, though it will target all space characters:

    "The      dog        has a long tail,      and it is RED!".replace(/\s\s+/g, ' ')
    
    "The dog has a long tail, and it is RED!"
    

    Edit: This is probably better since it targets a space followed by 1 or more spaces:

    "The      dog        has a long tail,      and it is RED!".replace(/  +/g, ' ')
    
    "The dog has a long tail, and it is RED!"
    

    Alternative method:

    "The      dog        has a long tail,      and it is RED!".replace(/ {2,}/g, ' ')
    "The dog has a long tail, and it is RED!"
    

    I didn't use /\s+/ by itself since that replaces spaces that span 1 character multiple times and might be less efficient since it targets more than necessary.

    I didn't deeply test any of these so lmk if there are bugs.

    Also, if you're going to do string replacement remember to re-assign the variable/property to its own replacement, eg:

    var string = 'foo'
    string = string.replace('foo', '')
    

    Using jQuery.prototype.text:

    var el = $('span:eq(0)');
    el.text( el.text().replace(/\d+/, '') )
    

提交回复
热议问题