我想从字符串的开头/结尾删除所有不必要的逗号.
例如; google, yahoo,, ,应该成为google, yahoo.
如果可能,google,, , yahoo,, ,应该成为google,yahoo.
我已经尝试了以下代码作为起点,但它似乎没有按预期工作.
trimCommas = function(s) {
s = s.replace(/,*$/, "");
s = s.replace(/^\,*/, "");
return s;
}
Run Code Online (Sandbox Code Playgroud)
rek*_*o_t 17
在您的示例中,如果逗号在开头或结尾处有空格,您还需要修剪逗号,使用如下所示的内容:
str.replace(/^[,\s]+|[,\s]+$/g, '').replace(/,[,\s]*,/g, ',');
Run Code Online (Sandbox Code Playgroud)
注意使用'g'修饰符进行全局替换.
你需要这个:
s = s.replace(/[,\s]{2,}/,""); //Removes double or more commas / spaces
s = s.replace(/^,*/,""); //Removes all commas from the beginning
s = s.replace(/,*$/,""); //Removes all commas from the end
Run Code Online (Sandbox Code Playgroud)
编辑:做出所有的改变 - 现在应该工作.