简体   繁体   中英

Remove last appeared comma in string using javascript

I have a text

test, text, 123, without last comma

I need it to be

test, text, 123 without last comma

(no comma after 123). How to achieve this using 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 . that matches any character but new line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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