Joris Ooms
Joris Ooms

Reputation: 12048

Help with a regular expression to capture numbers

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

Upvotes: 1

Views: 160

Answers (5)

Kobi
Kobi

Reputation: 138137

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.

Upvotes: 4

tonekk
tonekk

Reputation: 478

This also works:

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

Upvotes: 2

user742071
user742071

Reputation:

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

Upvotes: 1

Mo Valipour
Mo Valipour

Reputation: 13496

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.

Upvotes: 2

John B
John B

Reputation: 32969

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

Upvotes: 1

Related Questions