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.
JavaScript
x
15
15
1
var str = 'This, is a test.';
2
alert( removeLastComma(str) ); // should remain unchanged
3
4
var str = 'This, is a test,';
5
alert( removeLastComma(str) ); // should remove the last comma
6
7
var str = 'This is a test, ';
8
alert( removeLastComma(str) ); // should remove the last comma
9
10
function removeLastComma(strng){
11
var n=strng.lastIndexOf(",");
12
var a=strng.substring(0,n)
13
return a;
14
}
15
Advertisement
Answer
This will remove the last comma and any whitespace after it:
JavaScript
1
2
1
str = str.replace(/,s*$/, "");
2
It uses a regular expression:
The
/
mark the beginning and end of the regular expressionThe
,
matches the commaThe
s
means whitespace characters (space, tab, etc) and the*
means 0 or moreThe
$
at the end signifies the end of the string