1

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 regexTest.test("$2,000"); 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?

Community
  • 1
  • 1

2 Answers2

1

remove your ^ in regex. try this one

Also I recommend to remove $ as well so price like this $5.000,00 words will return true

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('$5,000.00'));
console.log(regexTest.test('$5,000.00 that was computer price'));
console.log(regexTest.test('computer 5,000.00'));
RizkiDPrast
  • 1,695
  • 1
  • 14
  • 21
0

The global modifier should work. Add the g after the last /

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

Should match with all instances inside the test string.

General Failure
  • 2,421
  • 4
  • 23
  • 49
m.crowley
  • 3
  • 3