删除JavaScript中不需要的逗号 [英] remove unwanted commas in JavaScript
本文介绍了删除JavaScript中不需要的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从字符串的开头/结尾删除所有不必要的逗号。
I want to remove all unnecessary commas from the start/end of the string.
例如; google,yahoo ,,
应该变成 google,yahoo
。
如果可能,google ,,,雅虎,,
应该变成 google,yahoo
。
我已尝试使用以下代码作为起点,但似乎无法正常工作。
I've tried the below code as a starting point, but it seems to be not working as desired.
trimCommas = function(s) {
s = s.replace(/,*$/, "");
s = s.replace(/^\,*/, "");
return s;
}
推荐答案
在你的例子中你也想要如果在开头或结尾处有空格,请修剪逗号,使用以下内容:
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, ',');
注意使用'g'修饰符进行全局替换。
Note the use of the 'g' modifier for global replace.
这篇关于删除JavaScript中不需要的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文