Thursday, December 23, 2004

Add/Remove Commas for Numbers in a textbox using JavaScript and RegEx Patterns

function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS:
strValue - Source string from which commas will
be removed;

RETURNS: Source string with commas removed.
*************************************************/

var objRegExp = /,/g; //search for commas globally

//replace all matches with empty strings
return strValue.replace(objRegExp,'');
}

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS:
strValue - source string containing commas.

RETURNS: String modified with comma grouping if
source was all numeric, otherwise source is
returned.

REMARKS: Used with integers or numbers with
2 or less decimal places.
*************************************************/
var objRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');

//check for match to search criteria
while(objRegExp.test(strValue)) {
//replace original string with first group match,
//a comma, then second group match
strValue = strValue.replace(objRegExp, '$1,$2');
}
return strValue;
}

No comments: