teggy
teggy

Reputation: 6315

jQuery: match currency with a regular expression

In the following:

<span>This cost $15.99 per item</span>

how do I return "$15.99" using jquery? The value can also be for example "$7".

Upvotes: 2

Views: 3293

Answers (5)

Aaron Butacov
Aaron Butacov

Reputation: 34347

$("span").filter(function() {
    return this.text().match('\$\d+(\.\d+)?');
});

You can use just the match of match('\$\d+(\.\d+)?'), but the above function will filter spans that contain the match.

Upvotes: 1

Don
Don

Reputation: 9661

The expression would be something similar to \$\d+(\.\d+)? or \$\d+(?:\.\d+)? to get rid of the sub group.

Upvotes: 2

jAndy
jAndy

Reputation: 236022

return($('span').text().match(/\$\d.+\d/));

example

Upvotes: 0

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

demo

alert($('span').text().match(/\$\d+.\d+/));

but there is a code here for the regex to be more precise...

Upvotes: 0

Tomas Aschan
Tomas Aschan

Reputation: 60584

Will the text always be "This cost [your price] per item", or is the text also arbitrary?

If the text is fixed, you can just $.replace() everything except the price (in two steps) with an empty string.

Upvotes: 0

Related Questions