3

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?

3 Answers 3

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Short, exact and with explanation! Thank you.
♡ Take that, oxford comma - muuuhahahahaha .replace(/,(?=[^,]*$)/, ' and')
9

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. :-)

1 Comment

:( didn't know that javasctipt has lastIndexOf.. Thanks!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.