Your
regex
replaces only single white space characters (
\s
) with a single space. To match sequences of multiple spaces, you have to specify that by appending a
+
(match one or more occurences) or
{2,}
(match two or more occurences).
There is also no need to use a loop when using the regex global option.
Finally, the
String.prototype.replace() - JavaScript | MDN[
^] function returns a new string where the replacement has been performed but
does not alter the original string
So use (untested):
function spaceremover(){
var a = document.getElementById("bar").value;
document.getElementById("result1").innerHTML = a.replace(/\s{2,}/g, ' ');
}