Search code examples
javascriptstringecmascript-6ecmascript-5

Is there better way than this to find and remove additional space in string in JS?


I have the following function which detects if there is 2 space and removes one:

filterText(text) {
    
        if (text.indexOf('  ') >= 0) {
          return text.replace('  ', ' ')
        }
        return text
      }
    

is there a better way to achieve the same result?


Solution

  • String.prototype.replace()

    If pattern is a string, only the first occurrence will be replaced.

    You can either use String.prototype.replaceAll() or try using RegEx with global flag.

    The following example will remove 2 or more spaces with single space:

    text = `some  text,  more      text`;
    text = text.replace(/\ +/g, ' ');
    console.log(text);

    If you want match exactly 2 space then:

    text = text.replace(/\ {2}/g, ' ');