Published:
Warning: This blog entry was written two or more years ago. Therefore, it may contain broken links, out-dated or misleading content, or information that is just plain wrong. Please read on with caution.
I thought I would switch it up this week with a little JS-101.
Here is a utility function I've had around for formatting numbers into comma separated strings. Since it uses a some regex I thought it might be of interest to someone who is just getting started with regular expressions.
function addCommas(num){
num = num.toString(); // Cast to a string so we can manipulate it
var numberSplit = num.split('.'); // Split the string into a whole number and decimal
var wholeNumber = numberSplit[0];
// If there is a decimal then create a string representation including a decimal point
var decimalComponent = numberSplit.length > 1 ? '.' + numberSplit[1] : '';
// Working from the end of the number string backwards
// capture numbers in groups of three where there is at least
// one other number before the grouping
var regularExpression = /(\d+)(\d{3})/;
while (regularExpression.test(wholeNumber)) {
// Insert the comma between the first group of numbers of unknown length
// and the immediate group of three numbers after it
wholeNumber = wholeNumber.replace(regularExpression, '$1' + ',' + '$2');
}
return wholeNumber + decimalComponent;
}
Reader Comments