Regex to replace multiple spaces with a single space

后端 未结 23 2326
北恋
北恋 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
    var string = "The dog      has a long   tail, and it     is RED!";
    var replaced = string.replace(/ +/g, " ");
    

    Or if you also want to replace tabs:

    var replaced = string.replace(/\s+/g, " ");
    
    0 讨论(0)
  • 2020-11-22 10:23

    is replace is not used, string = string.split(/\W+/);

    0 讨论(0)
  • 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, ' ');
    };
    
    0 讨论(0)
  • 2020-11-22 10:25

    For more control you can use the replace callback to handle the value.

    value = "tags:HUNT  tags:HUNT         tags:HUNT  tags:HUNT"
    value.replace(new RegExp(`(?:\\s+)(?:tags)`, 'g'), $1 => ` ${$1.trim()}`)
    //"tags:HUNT tags:HUNT tags:HUNT tags:HUNT"
    
    0 讨论(0)
  • 2020-11-22 10:28

    I know we have to use regex, but during an interview, I was asked to do WITHOUT USING REGEX.

    @slightlytyler helped me in coming with the below approach.

    const testStr = "I   LOVE    STACKOVERFLOW   LOL";
    
    const removeSpaces = str  => {
      const chars = str.split('');
      const nextChars = chars.reduce(
        (acc, c) => {
          if (c === ' ') {
            const lastChar = acc[acc.length - 1];
            if (lastChar === ' ') {
              return acc;
            }
          }
          return [...acc, c];
        },
        [],
      );
      const nextStr = nextChars.join('');
      return nextStr
    };
    
    console.log(removeSpaces(testStr));

    0 讨论(0)
提交回复
热议问题