I have a string that is like below.
,liger, unicorn, snipe,
how can I trim the leading and trailing comma in javascript?
Using the substring() method We remove the last comma of a string by using the built-in substring() method with first argument 0 and second argument string. length()-1 in Java. Slicing starts from index 0 and ends before last index that is string. length()-1 .
JavaScript has allowed trailing commas in array literals since the beginning, and later added them to object literals, and more recently, to function parameters and to named imports and named exports. JSON, however, disallows trailing commas.
replace(/\,/g,''); // 1125, but a string, so convert it to number a=parseInt(a,10); Hope it helps.
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.
If you want to make sure you don't have any trailing commas or whitespace, you might want to use this regex.
var str = ' , , , foo, bar, ';
str = str.replace(/(^[,\s]+)|([,\s]+$)/g, '');
returns
"foo, bar"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With