javascript 使用javascript删除字符串中最后出现的逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14355791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:26:04  来源:igfitidea点击:

Remove last appeared comma in string using javascript

javascriptregexstringcomma

提问by 0x49D1

I have a text

我有文字

test, text, 123, without last comma

测试,文本,123,没有最后一个逗号

Need it to be

需要它

test, text, 123 without last comma

测试,文本,123 没有最后一个逗号

(no comma after 123). How to achieve this using javasctipt?

(123 后没有逗号)。如何使用 javasctipt 实现这一点?

回答by georg

str.replace(/,(?=[^,]*$)/, '')

This uses a positive lookahead assertionto replace a comma followed only by non-commata.

这使用肯定的前瞻断言来替换后跟非逗号的逗号。

回答by T.J. Crowder

A non-regex option:

非正则表达式选项:

var str = "test, text, 123, without last comma";
var index = str.lastIndexOf(",");
str = str.substring(0, index) + str.substring(index + 1);

But I like the regex one. :-)

但我喜欢正则表达式之一。:-)

回答by nhahtdh

Another way to replace with regex:

另一种用正则表达式替换的方法:

str.replace(/([/s/S]*),/, '')

This relies on the fact that *is greedy, and the regex will end up matching the last ,in the string. [/s/S]matches any character, in contrast to .that matches any character but new line.

这依赖于*贪婪的事实,正则表达式最终将匹配,字符串中的最后一个。[/s/S]匹配任何字符,相比之下.,匹配除新行之外的任何字符。