I want to remove all unnecessary commas from the start/end of the string.
eg; google, yahoo,, ,
should become google, yahoo
.
If possible ,google,, , yahoo,, ,
should become google,yahoo
.
I've tried the below code as a starting point, but it seems to be not working as desired.
trimCommas = function(s) {
s = s.replace(/,*$/, "");
s = s.replace(/^\,*/, "");
return s;
}
First ping on Google for "Javascript Trim": http://www.somacon.com/p355.php. You seem to have implemented this using commas, and I don't see why it would be a problem (though you escaped in the second one and not in the first).
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:
The first one replaces every sequence of white space 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):
to collapse multi-spaces down to one space and
if you want them to be formatted nicely (space after each comma).
A more generalized solution would be to pass parameters to indicate behaviour:
true
forcollapse
will collapse the spaces within a section (a section being defined as the characters between commas).true
foraddSpace
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.
In your example you also want to trim the commas if there's spaces between them at the start or at the end, use something like this:
Note the use of the 'g' modifier for global replace.
Not quite as sophisticated, but simple with:
When you want to replace
",," ",,,", ",,,,"
and",,,,,"
below code will be removed by","
.You need this:
EDIT: Made all the changes - should work now.