0x49D1
0x49D1

Reputation: 8704

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?

Upvotes: 3

Views: 22930

Answers (3)

nhahtdh
nhahtdh

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

T.J. Crowder
T.J. Crowder

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

georg
georg

Reputation: 215059

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

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

Upvotes: 22

Related Questions