Skip to content Skip to sidebar Skip to footer

How Can I Remove Extra White Space In A String In JavaScript?

How can I remove extra white space (i.e. more than one white space character in a row) from text in JavaScript? E.g match the start using. How can I remove all but one of the

Solution 1:

Use regex. Example code below:

var string = 'match    the start using. Remove the extra space between match and the';
string = string.replace(/\s{2,}/g, ' ');

For better performance, use below regex:

string = string.replace(/ +/g, ' ');

Profiling with firebug resulted in following:

str.replace(/ +/g, ' ')        ->  790ms
str.replace(/ +/g, ' ')       ->  380ms
str.replace(/ {2,}/g, ' ')     ->  470ms
str.replace(/\s\s+/g, ' ')     ->  390ms
str.replace(/ +(?= )/g, ' ')    -> 3250ms

Solution 2:

See string.replace on MDN

You can do something like this:

var string = "Multiple  spaces between words";
string = string.replace(/\s+/,' ', g);

Solution 3:

Just do,

var str = "match    the start using. Remove the extra space between match and the";
str = str.replace( /\s\s+/g, ' ' );

Solution 4:

  function RemoveExtraSpace(value)
  {
    return value.replace(/\s+/g,' ');
  }

Solution 5:

myString = Regex.Replace(myString, @"\s+", " "); 

or even:

RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");

Post a Comment for "How Can I Remove Extra White Space In A String In JavaScript?"