Archive for June 15, 2007

JavaScript: How to Remove Comma from the End of a List

Posted in JavaScript, Regular Expressions, Software, Web, internet, programming on June 15, 2007 by Joey

Occasionally in JavaScript a list will be built using a loop. On each iteration of the loop a comma will be added to separate the current list item from the list item that will be added on the next iteration of the loop. For the final item of the list, however, there is not another value that will follow so the result is a list with an unneccessary comma at the end. This extraneous comma can easily be removed by using the JavaScript replace function, as illustrated in the following example:

var lstLetters = 'a,b,c,d,';
var lstReplace = lstLetters.replace(/\,$/,'');
document.write(lstReplace);

The regular expression in the replace function works like this:

The backslash(\) is used as an escape character so that the regular expression knows to look for a literal comma (i.e., the comma is not being used a separator).
The dollar sign ($) mean to only match a comma if it is at the end of the string. This will allow the necessary commas to remain.

Related Articles:
JavaScript Regular Expressions
JavaScript replace Function
JavaScript Regular Expression Backslash
JavaScript Regular Expression Special Characters: $ ^