简体   繁体   English

从字符串的开头和结尾删除多个逗号

[英]Remove multiple commas from start and end of string

Consider this scenario 考虑这种情况

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,,';

I want the respective outputs to be 我希望各自的输出是

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

Basically remove all the commas at the start and end of the string. 基本上删除字符串开头和结尾的所有逗号。 I was able to remove just one comma from the first and last of the string by trying couple of solutions from stack overflow but could not make it work. 通过尝试堆栈溢出中的几个解决方案,我只能从字符串的开头和结尾删除一个逗号,但无法使其正常工作。

Unified solution for removing trailing commas and possible spaces at the start and end of the string: 用于删除字符串开头和结尾的尾部逗号和可能空格的统一解决方案:

 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); 

You could match the part between the commas: 您可以匹配逗号之间的部分:

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

var edited = test.replace(/^,|,$/g,'');

^, matches the comma at the start of the string and ,$ matches the comma at the end. ^,匹配字符串开头的逗号,, $匹配字符串结尾的逗号。

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

source: remove starting and ending comma from variable in javascript 来源: 从javascript中的变量中删除开头和结尾的逗号

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM