Reputation: 65
Hi this is working now but I am confused at to why.
I am learning regex and need to pull the numbers out of strings like
'Discount 7.5%' should get 7.5
'Discount 15%' should get 15
'Discount 10%' should get 10
'Discount 5%' should get 5
etc.
/\d,?.\d?/ //works
/\d,?.\d,?/ //doesn't works
/\d?.\d?/ //doesn't works
I thought one of the second two would work could someone explain this.
Upvotes: 4
Views: 109
Reputation: 9654
IF you check this Regex, this is what you need so it will return the float number only if the word before it is Discount by making use of the lookbehind operator:
(?<=Discount\s)\d+(\.\d+)?
But the problem is that works with PHP(prce) I can't get it working with javascript.
EDIT: As mentioned in here regex and commas Javascript does not support lookbehind regex so here is what I did to work around it JS Fiddle
var div = document.getElementById('test');
var text = div.innerHTML;
div.innerHTML = text.replace(/Discount (.*)%/ig,'$1');
<div id="test">
Discount 7.5%<br>
Discount 15%<br>
discount 10%<br>
Discount 5.433%<br>
Fee 11%<br>
Discount 22.7%
</div>
As you see it does match it only if it was followedd by the word Discount, the word Fee 11%
does not match
Upvotes: 0
Reputation: 521249
You can use the following regex, which will match one or more digits, optionally followed by a decimal point and any number of digits:
^Discount\s(\d+(\.\d+)?)%$
Upvotes: -1
Reputation: 94319
Quick and dirty with easy to understand regex.
//Let the system to optimize the number parsing for efficiency
parseFloat(text.replace(/^\D+/, ""));
Demo: http://jsfiddle.net/DerekL/4bnp8381/
Upvotes: 2
Reputation: 7237
Try this. Make the second part with dot .
optional with ?
(\d)*(\.\d*)?
Upvotes: 0