删除字符串中第一次出现的逗号 [英] Remove first occurrence of comma in a string

查看:51
本文介绍了删除字符串中第一次出现的逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking for a way to remove the first occurrence of a comma in a string, for example

"some text1, some tex2, some text3"

应该返回:

"some text1 some text2, some tex3"

因此,该函数仅应查看是否有多个逗号,如果存在,则应删除第一个逗号.这可能可以用正则表达式解决,但是我不知道该怎么写,有什么想法吗?

So, the function should only look if there's more than one comma, and if there is, it should remove the first occurrence. This could be probably solved with the regex but I don't know how to write it, any ideas ?

推荐答案

这可以做到:

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

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

When you use the replace method with a string rather than an RE, it just replaces the first match.

这篇关于删除字符串中第一次出现的逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆