I need a function to remove all characters except numbers + characters: \'$\', \'.\' and \',\'.
How can I do this?
If you do not want to allow someone to type such values in a textbox then jQuery Numeric is a nice plugin that does exactly what you want,
> 'worth $12,345.00 dollars'.replace(/[^0-9$.,]/g, '')
"$12,345.00"
This is the answer you asked for. I would not recommend it for extracting currencies, since it can suffer from problems like this:
> 'A set of 12 worth between $123 and $456. A good buy.'.replace(/[^0-9$.,]/g, '')
"12$123$456.."
If you want to just extract expressions of a currency-like form, you could do:
> 'set of 12 worth between $123.00 and $45,678'.match(/\$[0-9,]+(?:\.\d\d)?/g)
["$123.00", "$45,678"]
If you need more complicated matching (e.g. you'd just like to extract the dollar value and ignore the cent value) you could do something like How do you access the matched groups in a JavaScript regular expression? for example:
> var regex = /\$([0-9,]+)(?:\.(\d\d))?/g;
> while (true) {
> var match = regex.exec('set of 12 worth between $123.00 and $45,678');
> if (match === null)
> break;
> console.log(match);
> }
["$123.00", "123", "00"]
["$45,678", "45,678", undefined]
(Thus be careful, javascript regexp objects are not immutable/final objects, but have state and can be used for iteration as demonstrated above. You thus cannot "reuse" a regexp object. Even passing myRegex2 = RegExp(myRegex)
will mix state; a very poor language decision for the constructor. See the addendum on how to properly clone regexes in javascript.) You can rewrite the above as a very exotic for-loop if you'd like:
var myString = 'set of 12 worth between $123.00 and $45,678';
var regex = '\$([0-9,]+)(?:\.(\d\d))?';
for(var match, r=RegExp(regex,'g'); match=regex.exec(myString) && match!==null; )
console.log(match);
addendum - Why you can't reuse javascript RegExp objects
Bad language design, demonstrating how state is reused:
var r=/(x.)/g
var r2 = RegExp(r)
r.exec('xa xb xc')
["xa", "xa"]
r2.exec('x1 x2 x3')
["x2", "x2"]
How to properly clone a regex in javascript (you have to define it with a string):
var regexTemplate = '(x.)'
var r = RegExp(regexTemplate, 'g')
var r2 = RegExp(regexTemplate, 'g')
r.exec('xa xb xc')
["xa", "xa"]
r2.exec('x1 x2 x3')
["x1", "x1"]
If you wish to programmatically preserve flags such as 'g'
, you can probably use regexTemplate = ['(x.)', 'g']; RegExp.apply(this, regexTemplate)
.