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

时间:2014-05-31 12:29:07

标签: javascript regex

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

"some text1, some tex2, some text3"

应该返回:

"some text1 some text2, some tex3"

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

5 个答案:

答案 0 :(得分:20)

这样做:

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

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

答案 1 :(得分:10)

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

"some text1, some tex2, some text3".replace(',', '')
// => "some text1 some tex2, some text3"

仅当您使用g标志指定正则表达式时才会进行全局替换。


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

答案 2 :(得分:2)

简单的一个班轮就可以了:

text = text.replace(/^(?=(?:[^,]*,){2})([^,]*),/, '$1');

以下是它的工作原理:

regex = re.compile(r"""
    ^                # Anchor to start of line|string.
    (?=              # Look ahead to make sure
      (?:[^,]*,){2}  # There are at least 2 commas.
    )                # End lookahead assertion.
    ([^,]*)          # $1: Zero or more non-commas.
    ,                # First comma is to be stripped.
    """, re.VERBOSE)

答案 3 :(得分:1)

分裂的方式:

var txt = 'some text1, some text2, some text3';

var arr = txt.split(',', 3);

if (arr.length == 3)
    txt = arr[0] + arr[1] + ',' + arr[2];

或更短:

if ((arr = txt.split(',', 3)).length == 3)
    txt = arr[0] + arr[1] + ',' + arr[2];

如果数组中少于3个元素(少于2个逗号),则字符串保持不变。 split方法使用limit参数(设置为3),一旦达到3个元素的限制,split方法就会停止。

或替换:

txt = txt.replace(/,(?=[^,]*,)/, '');

答案 4 :(得分:1)

你也可以像^(.*?),(?=.*,)那样使用前瞻,并替换w $1
Demo

相关问题