You should use a regex to get all spaces and replace it with one
string.replace(/\s\s+/g, " ");
If you only want it to work on a space and not tabs, use this:
string.replace(/ +/g, " ");
In the regex world "+" means 1 and any more that follow it. The "g" at the end means "global", or do it more than once. Removing the g would replace the first string of spaces but not any others. "\s" means all space-type characters which includes " " and tabs.