tags:

views:

706

answers:

3

I have a string that is like below.

,liger, unicorn, snipe,

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

+9  A: 

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'
cobbal
Now you have two problems...
eyelidlessness
(Note: I upvoted this answer, I just like trite sayings.)
eyelidlessness
+5  A: 

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>
paxdiablo
+1 for the RE comment.
Raithlin
Thanx Pax it works
santanu
Ask not what REs can do for you, but what you can do for REs! :)
cobbal
+6  A: 

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.

eyelidlessness