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

前端 未结 5 1283
忘掉有多难
忘掉有多难 2020-12-13 01:58

I have a string that is like below.

,liger, unicorn, snipe,

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

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 02:45

    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"
    

提交回复
热议问题