What you need to do is replace all groups of "space and comma" with a single comma and then remove commas from the start and end:
trimCommas = function(s) {
s = s.replace(/[,\s]*,[,\s]*/g, ",");
s = s.replace(/^,/, "");
s = s.replace(/,$/, "");
return s;
}
The first one replaces every sequence of whitespace and commas with a single comma, provided there's at least one comma in there. This handles the edge case left in the comments for "Internet Explorer".
The second and third get rid of the comma at the start and end of string where necessary.
You can also add (to the end):
s = s.replace(/[\s]+/, " ");
to collapse multi-spaces down to one space and
s = s.replace(/,/g, ", ");
if you want them to be formatted nicely (space after each comma).
A more generalized solution would be to pass parameters to indicate behavior:
- Passing
true
for collapse
will collapse the spaces within a section (a section being defined as the characters between commas).
- Passing
true
for addSpace
will use ", "
to separate sections rather than just ","
on its own.
That code follows. It may not be necessary for your particular case but it might be better for others in terms of code re-use.
trimCommas = function(str,collapse,addspace) {
s = s.replace(/[,\s]*,[,\s]*/g, ",").replace(/^,/, "").replace(/,$/, "");
if (collapse) {
s = s.replace(/[\s]+/, " ");
}
if (addspace) {
s = s.replace(/,/g, ", ");
}
return s;
}