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.
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
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>
Try this regex
var st = "hello world".replace(/\s/g,'');
or as a function
function removeSpace(str){
return str.replace(/\s/g,'');
}
Here is a working demo