从string的开头和结尾删除多个逗号

考虑这种情况

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 

基本上删除string的开始和结束的所有逗号。 我能够从string的第一个和最后一个string中删除一个逗号,尝试从堆栈溢出几个解决scheme,但不能使其工作。

你可以匹配逗号之间的部分:

 const re = /^,*(.*?),*$/; const data = ',,,^^ranbir$$this is first comment,,'; const result = data.match(re); console.log(result[1]); 

用于删除string开头和结尾的尾随逗号和可能空格的统一解决scheme:

 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); 
 var edited = test.replace(/^,|,$/g,''); 

^,匹配string开头的逗号,$匹配最后的逗号。

伪代码:while foo contains(foo.replace(/ ^,|,$ / g,''));

源: 从JavaScript中的variables中删除开始和结束逗号