How can I trim the leading and trailing comma in javascript?

because I believe everything can be solved with regex:

var str = ",liger, unicorn, snipe,"
var trim = str.replace(/(^,)|(,$)/g, "")
// trim now equals 'liger, unicorn, snipe'

While cobbal's answer is the "best", in my opinion, I want to add one note: Depending on the formatting of your string and purpose of stripping leading and trailing commas, you may also want to watch out for whitespace.

var str = ',liger, unicorn, snipe,';
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');

Of course, with this application, the value of using regex over basic string methods is more obvious.

Tags:

Javascript