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"?
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"?
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);
Just do,
var str = "match the start using. Remove the extra space between match and the";
str = str.replace( /\s\s+/g, ' ' );
myString = Regex.Replace(myString, @"\s+", " ");
or even:
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"[ ]{2,}", options);
tempo = regex.Replace(tempo, @" ");
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
Sure, using a regex:
var str = "match the start using. Remove the extra space between match and the";
str = str.replace(/\s/g, ' ')
This can be done also with javascript logic.
here is a reusable function I wrote for that task.
LIVE DEMO
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>result:
<span id="spn">
</span>
</div>
<input type="button" value="click me" onClick="ClearWhiteSpace('match the start using. JAVASCRIPT CAN BE VERY FUN')"/>
<script>
function ClearWhiteSpace(text) {
var result = "";
var newrow = false;
for (var i = 0; i < text.length; i++) {
if (text[i] === "\n") {
result += text[i];
// add the new line
newrow = true;
}
else if (newrow == true && text[i] == " ") {
// do nothing
}
else if (text[i - 1] == " " && text[i] == " " && newrow == false) {
// do nothing
}
else {
newrow = false;
if (text[i + 1] === "\n" && text[i] == " ") {
// do nothing it is a space before a new line
}
else {
result += text[i];
}
}
}
alert(result);
document.getElementById("spn").innerHTML = result;
return result;
}
</script>
</body>
</html>