Skip to content
Advertisement

Remove last comma (and possible whitespaces after the last comma) from the end of a string

Using JavaScript, how can I remove the last comma, but only if the comma is the last character or if there is only white space after the comma? This is my code. I got a working fiddle. But it has a bug.

var str = 'This, is a test.'; 
alert( removeLastComma(str) ); // should remain unchanged

var str = 'This, is a test,'; 
alert( removeLastComma(str) ); // should remove the last comma

var str = 'This is a test,          '; 
alert( removeLastComma(str) ); // should remove the last comma

function removeLastComma(strng){        
    var n=strng.lastIndexOf(",");
    var a=strng.substring(0,n) 
    return a;
}

Advertisement

Answer

This will remove the last comma and any whitespace after it:

str = str.replace(/,s*$/, "");

It uses a regular expression:

  • The / mark the beginning and end of the regular expression

  • The , matches the comma

  • The s means whitespace characters (space, tab, etc) and the * means 0 or more

  • The $ at the end signifies the end of the string

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement