We help IT Professionals succeed at work.

JavaScript: Remove last comma

hankknight used Ask the Experts™
Using JavaScript, how can I remove the last comma in a string, regardless of its position?

var xyz = 'Hello, this is a test, and it is only a test.';
alert( zapLastComma(xyz) ); // Hello, this is a test and it is only a test.

var xyz = 'Hello,';
alert( zapLastComma(xyz) ); // Hello

var xyz = 'Hello,\nThis is a test,\nand only a test.';
alert( zapLastComma(xyz) ); 

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Format zapLastComma() function as follows:
function zapLastComma(str)
   str=str.replace(/, /g," ");
   return str.replace(/,*$/g,"");

Open in new window

Top Expert 2011
Please try:
function zapLastComma(s){
	var i = s.lastIndexOf(",");

	if (i == 0)
		s = s.substr(i);
	else if (i > 0)
		s = s.substr(0, i) + s.substr(i + 1);

	return s;

Open in new window

Consultant & Challenge Subduer
Top Expert 2009
@experts1  Your code will remove multiple commas. Also this can be done with a single call to replace().

@wdosanjos  Your code doesn't seem to work as intended when "i" is 0. By the way, are you aware that substr() isn't included in the 3rd edition of ECMAScript like slice() and substring() are?

Here are two functions that will remove the last comma:
function zapLastComma(s) {
	var i=s.lastIndexOf(',');
	return (i>-1)?s.slice(0,i)+s.slice(i+1):s;

Open in new window

function zapLastComma(s) {
  return s.replace(/,([^,]*)$/,'$1');

Open in new window