Try something like this:
var new_string = old_string.replace(/[\s,]+/g,' ').trim();
The regex is simply [\s,]+
if we were to break this down the \s
means ANY whitespace character and ,
is a literal comma. The []
is a character set (think array) and the +
means one or more matches.
If you just wanted a space and not any whitespace, you could replace the \s
with a literal space as well.
We throw in a /g
on the end so that it does a global search and replace, otherwise it'd just do it for one match only.