Reputation: 10981
I have the following variable which is the selected text of a select box. This is the select box markup.
<select name="SELECT___100E___7">
<option selected="" value="25">Beige/Almond</option>
<option value="21">Blue [Subtract -$1.00]</option>
<option value="27">Chrome [Subtract -$2.00]</option>
<option value="29">Red [Add $1.00]</option>
</select>
Variable test_var hold the selected text...
$('select[name^="SELECT___"]').change(function(){
var test_var = $(this).find("option:selected").text();
});
So what I would like to do is remove all characters except for the amount, also removing the "$". So if "Red [Add $1.00]" is selected I want to have test_var equal to 1.00
Having trouble figuring out the regexp to do this.
Upvotes: 1
Views: 452
Reputation: 322492
Perhaps a cleaner approach is to simply use a custom attribute:
<option value="21" data-amount="1.00">Blue [Subtract -$1.00]</option>
Then use .attr()
:
$(this).find("option:selected").attr('data-amount');
Original answer: As @T.J. Crowder noted, this removes the -
, which is likely needed. If not, this would work.
While you could use a regex, you wouldn't need to.
If you know you'll have that layout of text, you could do something like this:
var result = test_var.split('$')[1].slice(0,-1);
It will split on the $
, then remove the last character ]
.
Upvotes: 2
Reputation: 1074295
This should do it (er, actually, see the update below):
var m = test_var.match(/(-?)\$([0-9\.]+)/);
var result = m.length > 0 ? m[1] : "";
What that says is "look for a $
followed by a series of digits and .
characters, and grab as many of that series as you can when matching." The resulting match array will have the complete matching string (including the $
in position 0, and then the first (and only) capture group at position 1 — and so we grab that.
Update Er, um, if you need to capture the -
sign (and I'm guessing you do), change that to this:
var m = test_var.match(/(-?)\$([0-9\.]+)/);
var result = m.length > 0 ? m[1] + m[2] : "";
That uses an optional capture for the -
if it's present before the $
, and then combines the two capture groups (m[1]
and m[2]
; m[1]
will be "" if there's no -
).
Results (for example):
Red [Add $1.00] => 1.00 Blue [Subtract -$1.00] => -1.00
Off-topic: Beware localization! Because in some locales, those .
s will be ,
s, e.g., "€1,00" for one Euro in Germany.
Upvotes: 2