考虑这种情况
var str1 = '^^ranbir$$this is first comment,,';
var str2 = ',,^^check$$this is another comment,,';
var str3 = ',,^^mike$$this is 3rd comment, but this is not the last one,,';
我希望各自的输出为
console.log(str1) // ^^ranbir$$this is first comment
console.log(str2) // ^^check$$this is another comment
console.log(str3) // ^^mike$$this is 3rd comment, but this is not the last one
基本上删除字符串开头和结尾的所有逗号。通过从堆栈溢出中尝试几个解决方案但是无法使其工作,我能够从字符串的第一个和最后一个中删除一个逗号。
答案 0 :(得分:2)
统一解决方案,用于删除字符串开头和结尾的尾随逗号和可能的空格:
var str3 = ',,, ^^mike$$this is 3rd comment, but this is not the last one ,,,, ',
replaced = str3.replace(/^\s*,+\s*|\s*,+\s*$/g, '');
console.log(replaced);
答案 1 :(得分:1)
您可以匹配逗号之间的部分:
const re = /^,*(.*?),*$/;
const data = ',,,^^ranbir$$this is first comment,,';
const result = data.match(re);
console.log(result[1]);
答案 2 :(得分:0)
var edited = test.replace(/^,|,$/g,'');
^,匹配字符串开头的逗号,$匹配结尾的逗号。
伪代码:foo包含(foo.replace(/ ^,|,$ / g,''));
来源:remove starting and ending comma from variable in javascript