Reputation: 8704
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?
Upvotes: 3
Views: 22930
Reputation: 56829
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.
Upvotes: 1
Reputation: 1075925
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. :-)
Upvotes: 9
Reputation: 215059
str.replace(/,(?=[^,]*$)/, '')
This uses a positive lookahead assertion to replace a comma followed only by non-commata.
Upvotes: 22