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.
Sure, using a regex:
var str = "match the start using. Remove the extra space between match and the";
str = str.replace(/\s/g, ' ')
function RemoveExtraSpace(value)
{
return value.replace(/\s+/g,' ');
}
Just do,
var str = "match the start using. Remove the extra space between match and the";
str = str.replace( /\s\s+/g, ' ' );
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
See string.replace on MDN
You can do something like this:
var string = "Multiple spaces between words";
string = string.replace(/\s+/,' ', g);
myString = Regex.Replace(myString, @"\s+", " ");
or even:
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);
tempo = regex.Replace(tempo, @" ");