Search code examples
javascriptregex

How to remove duplicate white spaces in a string?


Possible Duplicate:
Replace multiple whitespaces with single whitespace in JavaScript string

I have used trim function to remove the white spaces at the beginning and end of the sentences. If there is to much white spaces in between words in a sentence, is there any method to trim?

for example

"abc                  def. fds                            sdff."

Solution

  • try

    "abc                  def. fds                            sdff."
     .replace(/\s+/g,' ')
    

    or

    "abc                  def. fds                            sdff."
         .split(/\s+/)
         .join(' ');
    

    or use this allTrim String extension

    String.prototype.allTrim = String.prototype.allTrim ||
         function(){
            return this.replace(/\s+/g,' ')
                       .replace(/^\s+|\s+$/,'');
         };
    //usage:
    alert(' too much whitespace     here   right?  '.allTrim());
       //=> "too much whitespace here right?"
    

    [edit 2023] Pretty old answer. Here is a parser function to remove all multiple spaces (and spaces only, not whitespace) from a string, which removes the need for a regular expression.

    const line = ` hello     world
              how  are    you
           
        😃 and bye again  `;
    
    console.log(`[${removeDoubleSpaces(line)}]`);
    console.log(`[${removeDoubleSpaces(line, true)}]`);
    console.log(`[${removeDoubleSpaces(line, true, true)}]`);
    console.log(`[${removeDoubleSpaces(line, false, true)}]`);
    
    function removeDoubleSpaces(str, trimLines = false, removeLF = false) {
      let strResult = ``;
      const strCopy = [...str];
      
      while(strCopy.length) {
        const chr = strCopy.shift();
        strResult += removeLF && chr === `\n`  ? ` ` :
          strResult.at(-1) + chr !== `  ` ? chr : ``;
        // double line ends may result in double spaces
        strResult = strResult.slice(-2) === `  `
          ? strResult.slice(0, -1) : strResult;
      }
      
      return trimLines
        ? strResult.split(/\n/).map(v => v.trim()).join(`\n`)
        : strResult.trim();
     
     
    }
    .as-console-wrapper {
        max-height: 100% !important;
    }