[英]Remove last appeared comma in string using javascript
I have a text我有一段文字
test, text, 123, without last comma
测试,文本,123,没有最后一个逗号
I need it to be我需要它
test, text, 123 without last comma
测试,文本,123 没有最后一个逗号
(no comma after 123). (123 后没有逗号)。 How to achieve this using JavaScript?
如何使用 JavaScript 实现这一点?
str.replace(/,(?=[^,]*$)/, '')
这使用肯定的前瞻断言来替换逗号,后跟非逗号。
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 .但我喜欢正则表达式。 :-)
:-)
Another way to replace with regex:用正则表达式替换的另一种方法:
str.replace(/([/s/S]*),/, '$1')
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 .
[/s/S]
匹配任何字符,而.
that matches any character but new line.匹配除新行之外的任何字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.