gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:45:06 28 4
gpt4 key购买 nike

考虑这个场景

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

基本上删除字符串开头和结尾的所有逗号。通过尝试堆栈溢出的几种解决方案,我能够从字符串的第一个和最后一个逗号中删除一个逗号,但无法使其工作。

最佳答案

删除字符串开头和结尾的尾随逗号和可能的空格的统一解决方案:

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

关于javascript - 从字符串的开头和结尾删除多个逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41260197/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com