Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

I have a string that is like below.

,liger, unicorn, snipe,

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

like image 281
santanu Avatar asked Mar 19 '09 07:03

santanu


People also ask

How do you remove the comma at the end?

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 .

Does JavaScript allow trailing commas?

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.

How do I remove a comma from a number in typescript?

replace(/\,/g,''); // 1125, but a string, so convert it to number a=parseInt(a,10); Hope it helps.


3 Answers

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'
like image 172
cobbal Avatar answered Oct 17 '22 20:10

cobbal


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.

like image 40
eyelidlessness Avatar answered Oct 17 '22 22:10

eyelidlessness


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"
like image 33
herostwist Avatar answered Oct 17 '22 20:10

herostwist