Remove last appeared comma in string using javascript

20,799

Solution 1

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

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

Solution 2

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

Solution 3

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.

Share:
20,799
0x49D1
Author by

0x49D1

Console.WriteLine("Another C# developer with blog on https://t.me/x4516");

Updated on January 17, 2020

Comments

  • 0x49D1
    0x49D1 over 4 years

    I have a text

    test, text, 123, without last comma

    Need it to be

    test, text, 123 without last comma

    (no comma after 123). How to achieve this using javasctipt?