0

I need to detect currency and extract digit from such strings as "10 dollars", "dollars 10", etc. I use String.prototype.match() and regex

/((dollar|usd\$)\s*(\d+)|(\d+)\s*(dollar|usd\$))/i

But match() returns me for "10 dollars"

["10 dollar", "10 dollar", undefined, undefined, "10", "dollar"]

and for "dollar 10"

["dollar 10", "dollar 10", "dollar", "10", undefined, undefined]

How I can avoid that situation and get predictable digit position ?

2
  • You may check which group matched. Commented Jan 13, 2017 at 6:59
  • Super simple /(\d+)\ (dollar|usd)|(dollar|usd)\ (\d+)/gi Commented Jan 13, 2017 at 7:03

2 Answers 2

2

You may check which group matched and then grab the necessary value.

I suggest simplifying the structure a bit by turning alternations to non-capturing groups and removing the outer group:

/(?:dollars?|usd\$)\s*(\d+)|(\d+)\s*(?:dollars?|usd\$)/i

See this demo

A demo test:

var re = /(?:dollars?|usd\$)\s*(\d+)|(\d+)\s*(?:dollars?|usd\$)/i;
var strs = ["10 dollars", "dollars 30"];
for(var t of strs) {
  var m = t.match(re);
  if (m && m[2]) 
    console.log(m[2]);
  else if (m) console.log(m[1]);
 
}

Sign up to request clarification or add additional context in comments.

Comments

1

You can mark any group (things in (parentheses)) in a regex as "non-capturing" by adding ?: after the left paren, as in (?:non|capturing|group).

So if all you want is the digits, not the word "dollar" or "usd", you could do:

/(?:(?:dollar|usd\$)\s*(\d+)|(\d+)\s*(?:dollar|usd\$))/i

That will give you ["dollar 10", undefined, "10"] for "10 dollars". From there, just do:

var matches = myString.match(/(?:(?:dollar|usd\$)\s*(\d+)|(\d+)\s*(?:dollar|usd\$))/i);    
var amount = matches[2] || matches[1];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.