删除字符串中第一次出现的逗号

Zed*_*Zed 14 javascript regex

我正在寻找一种方法来删除字符串中第一次出现的逗号,例如

"some text1, some tex2, some text3"
Run Code Online (Sandbox Code Playgroud)

应该返回:

"some text1 some text2, some tex3"
Run Code Online (Sandbox Code Playgroud)

因此,该函数应仅查看是否有多个逗号,如果有,则应删除第一个匹配项.这可能可以通过正则表达式解决,但我不知道如何写它,任何想法?

Bar*_*mar 22

这样做:

if (str.match(/,.*,/)) { // Check if there are 2 commas
    str = str.replace(',', ''); // Remove the first one
}
Run Code Online (Sandbox Code Playgroud)

当您使用replace带有字符串而不是RE的方法时,它只是替换第一个匹配.


fal*_*tru 11

String.prototype.replace 仅替换匹配的第一次出现:

"some text1, some tex2, some text3".replace(',', '')
// => "some text1 some tex2, some text3"
Run Code Online (Sandbox Code Playgroud)

只有在使用gflag 指定正则表达式时才会发生全局替换.


var str = ",.,.";
if (str.match(/,/g).length > 1) // if there's more than one comma
    str = str.replace(',', '');
Run Code Online (Sandbox Code Playgroud)