jQuery Data Type How to - Remove extra space in a string








Question

We would like to know how to remove extra space in a string.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
var string ="how    are you today";
var array = string.split(" ");
string = "";<!--from   ww w  .  j a v a2 s  .  co  m-->
for(var i=0; i<array.length; i++)
{
    if(array[i] != "")
    {
        string += array[i];
        if(i<array.length-1) 
           string += " ";
    }
}
document.writeln(string);
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: