remove unwanted commas in JavaScript

后端 未结 9 1602
青春惊慌失措
青春惊慌失措 2020-12-14 13:14

I want to remove all unnecessary commas from the start/end of the string.

eg; google, yahoo,, , should become google, yahoo.

If pos

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 13:43

    In your example you also want to trim the commas if there's spaces between them at the start or at the end, use something like this:

    str.replace(/^[,\s]+|[,\s]+$/g, '').replace(/,[,\s]*,/g, ',');
    

    Note the use of the 'g' modifier for global replace.

提交回复
热议问题