Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  25] [ 6]  / answers: 1 / hits: 31430  / 12 Years ago, sun, march 18, 2012, 12:00:00

I need a function to remove all characters except numbers + characters: '$', '.' and ','.



How can I do this?


More From » jquery

 Answers
257
> '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,]+(?:.dd)?/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,]+)(?:.(dd))?/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,]+)(?:.(dd))?';

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).


[#86764] Friday, March 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;