tags:

views:

75

answers:

5

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".

+1  A: 

$("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.

Aaron Harun
`match('\$[0-9\.]+')`, will also match `$15.99.99`
Reigel
+1  A: 

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

Don
This is the correct one; why was this down voted?
Amarghosh
I did not down-vote it, but this would match two strings [0] = $15.99 and [1] = .99...
Reigel
I hardly ever work with javascript regex and wasn't sure if it supported non-capturing groups so left it out, but a quick googling says it does support it so added a second version with that.
Don
I was going to add the exact same answer as your second one with non-capturing groups. Good thing I didn't :) +1
Anurag
@Reigel What's wrong with capturing the second part - use it if you want or else just ignore it.
Amarghosh
@Amarghosh - yeah, nothing really... I was just thinking maybe that's the cause of the down-vote..
Reigel
A: 

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.

Tomas Lycken
A: 
return($('span').text().match(/\$\d.+\d/));

example

jAndy
This will match `$1asd3`, `$1 to $3`, `$1 and 2` and this won't match `$1` and `$12` - it needs part after $ to be at least 3 chars long
Amarghosh
A: 

demo

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

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

Reigel
Won't match `$7` as required in the question.
Amarghosh
yes, it's not precise.. just like all the answers provided... I did post a link for more precise regex though....
Reigel