Regex to replace multiple spaces with a single space

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

    This script removes any white space (multiple spaces, tabs, returns, etc) between words and trims:

    // Trims & replaces any wihtespacing to single space between words
    String.prototype.clearExtraSpace = function(){
      var _trimLeft  = /^\s+/,
          _trimRight = /\s+$/,
          _multiple  = /\s+/g;
    
      return this.replace(_trimLeft, '').replace(_trimRight, '').replace(_multiple, ' ');
    };
    

提交回复
热议问题