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

Javascript

Javascript Problem Overview


I have a string that is like below.

,liger, unicorn, snipe,

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

Javascript Solutions


Solution 1 - 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'

Solution 2 - Javascript

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.

Solution 3 - Javascript

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"

Solution 4 - Javascript

Try this, since not everything can be solved by REs and even some things that can, shouldn't be :-)

<script type="text/javascript">
    var str = ",liger, unicorn, snipe,";
    if (str.substr(0,1) == ",") {
        str = str.substring(1);
    }
    var len = str.length;
    if (str.substr(len-1,1) == ",") {
        str = str.substring(0,len-1);
    }
    alert (str);
</script> 

Solution 5 - Javascript

In ECMAScript 5 and above, you can now do a one-liner

',liger, unicorn, snipe,'.split(',').map(e => e.trim()).filter(e => e).join(', ')

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsantanuView Question on Stackoverflow
Solution 1 - JavascriptcobbalView Answer on Stackoverflow
Solution 2 - JavascripteyelidlessnessView Answer on Stackoverflow
Solution 3 - JavascriptherostwistView Answer on Stackoverflow
Solution 4 - JavascriptpaxdiabloView Answer on Stackoverflow
Solution 5 - JavascriptchernjieView Answer on Stackoverflow