1

I need to capture the price out of the following string:

Price: 30.

I need the 30 here, so I figured I'd use the following regex:

([0-9]+)$

This works in Rubular, but it returns null when I try it in my javascript.

console.log(values[1]);
// Price: 100
var price = values[1].match('/([0-9]+)$/g');
// null

Any ideas? Thanks in advance

5 Answers 5

4

Try this:

var price = values[1].match(/([0-9]+)$/g);

JavaScript supports RegExp literals, you don't need quotes and delimiters.
.match(/\d+$/) should behave the same, by the way.

See also: MDN - Creating a Regular Expression

Keep in mind there are simpler ways of getting this data. For example:

var tokens = values[1].split(': ');
var price = tokens[1];

You can also split by a single space, and probably want to add some validation.

1
  • Doh. No quotes in match(). Thanks ;D
    – Joris Ooms
    Sep 7, 2011 at 11:29
2

Why don't you use this?

var matches = a.match(/\d+/);

then you can consume the first element (or last)

my suggestion is to avoid using $ in the end because there might be a space in the end.

1
  • Okay. Can you explain what that actually means? I'm new to the whole regex deal, so I was just trying in rubular till I got something that worked, haha.
    – Joris Ooms
    Sep 7, 2011 at 11:30
2

This also works:

var price = values[1].match('([0-9]+)$');

1

It appears that you escaped the open-perens and therefore the regex is looking for "(90".

0
1

You don't need to put quotes around the regular expression in JavaScript.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.