繁体   English   中英

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

[英]Remove first occurrence of comma in a string

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

"some text1, some tex2, some text3"

应该返回:

"some text1 some text2, some tex3"

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

这样做:

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

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

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

一个简单的衬里将做到这一点:

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)

分裂的方式:

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(/,(?=[^,]*,)/, '');

你也可以使用这样的前瞻^(.*?),(?=.*,)并替换w / $1
演示

暂无
暂无

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

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