Jordan Choo Jordan Choo - 1 year ago 73
Javascript Question

Does a string contain a price?

I'd like to check whether or not a string such as "The computer costs $2,000" contains a price or not.

I slightly modified this regex to fit my needs and the current regex that I am using looks like this:

var regexTest = /(?=.)^\$(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/;

If I do
it will return true. However, if I add additional characters to the string such as
regexTest.test("The computer costs $2,000");
it will return false.

How should I modify the regex code in order to return true for the second example?

Answer Source

remove your ^ in regex. try this one

var regexTest = /(?=.)\$(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/;

console.log(regexTest.test('computer $5,000.00'));
console.log(regexTest.test('computer 5,000.00'));

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download