Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove extra white space in a string in JavaScript?

Tags:

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 spaces between "match" and "the"?

like image 576
ankur Avatar asked Oct 03 '13 09:10

ankur


People also ask

How do I get rid of extra white spaces in a string?

The replaceAll() method of the String class replaces each substring of this string that matches the given regular expression with the given replacement. You can remove white spaces from a string by replacing " " with "".

What is the method in JavaScript used to remove the white space?

trim() The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.)


6 Answers

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
like image 56
Rajesh Avatar answered Oct 04 '22 07:10

Rajesh


See string.replace on MDN

You can do something like this:

var string = "Multiple  spaces between words";
string = string.replace(/\s+/,' ', g);
like image 44
omgmog Avatar answered Oct 04 '22 08:10

omgmog


Just do,

var str = "match    the start using. Remove the extra space between match and the";
str = str.replace( /\s\s+/g, ' ' );
like image 37
Ajith S Avatar answered Oct 04 '22 07:10

Ajith S


  function RemoveExtraSpace(value)
  {
    return value.replace(/\s+/g,' ');
  }
like image 23
Adarsh Kumar Avatar answered Oct 04 '22 08:10

Adarsh Kumar


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

or even:

RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);     
tempo = regex.Replace(tempo, @" ");
like image 28
Waqas Idrees Avatar answered Oct 04 '22 07:10

Waqas Idrees


Using regular expression.

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

Here is jsfiddle for this

like image 20
Ashok Avatar answered Oct 04 '22 06:10

Ashok