Zacharia Mwangi
Zacharia Mwangi

Reputation: 53

Javascript Regex to match currency

I want to find and match currency in a given text. Formats that are accepted are:

This is my regex so far:

var money_vals =  $('body').text().match(/\$\d+\.?\d+(\,\d+)?(thousand|million|billion|trillion)?/g);

However, it doesn't match $2 billion or the $625 million or any value followed by million/billion/trillion. Also, after adding $5 to one of the paragraphs in my text, I realized it doesn't get matched.

Could anyone please help?

Upvotes: 0

Views: 935

Answers (3)

Tiberiu C.
Tiberiu C.

Reputation: 3513

A generic form, group 1 matches the number second group the following boundary word

\$[\s]?([\d\.\,]+)[\s]*([\w]*)

http://regexr.com/3c3av

An exact match form :

\$[\s]?([\d\.\,]+)[\s]*(thousand|million|billion|trillion)?

http://regexr.com/3c3as

Upvotes: 2

Yash
Yash

Reputation: 1436

Try This

var re = /\$[0-9]+[?:, 0-9]*(?:billion|million+)?/;
var sourcestring = "source string to match with pattern";
var results = [];
var i = 0;
for (var matches = re.exec(sourcestring); matches != null; matches = re.exec(sourcestring)) {
 results[i] = matches;
for (var j=0; j<matches.length; j++) {
  alert("results["+i+"]["+j+"] = " + results[i][j]);
}
i++;

}

This will solve your problem.

Upvotes: 0

Mayur Koshti
Mayur Koshti

Reputation: 1852

You should use the following regex:

/\$\d+[\,\.\d\s]*(?:thousand|million|billion|trillion|$)/ig

Upvotes: 0

Related Questions