Reputation: 7040
I have a input field, whether i want to input percent value or flat amount for this i have to check it has ends with % sign or not.
sample input may be
12%
12.888%
12.00%
12.00001%
12.123344%
or for flat amount
100
100.55252
100.254575
something like this.
N.B: I want to learn javascript regex ...have any suggestions?
Upvotes: 3
Views: 14241
Reputation: 179
All of the previous suggestions are excellent. Depending on your needs, you can choose any of them. I added a bit more to the following to break out the value for you. Modify to suit your needs.
function getValue(num) {
var matches=num.match(/(^\s*\d+\.?\d*)(%)?\s*$/);
var m = false, p = false, v = 0;
if (matches) {
m = true;
p = (matches[2]=="%");
v = matches[1];
}
return {isMatch: m, isPercent: p, value: v};
}
var vals = "12%,12.888%,12.00%,12.00001%,12.123344%,100,100.,100.55252,100.254575,notnum".split(',');
for(var i=0;i<vals.length;i++) {
var gv = getValue(vals[i]);
console.log("string="+vals[i]," isMatch="+gv.isMatch," isPercent="+gv.isPercent," value="+gv.value);
}
Output is:
string=12% isMatch=true isPercent=true value=12
string=12.888% isMatch=true isPercent=true value=12.888
string=12.00% isMatch=true isPercent=true value=12.00
string=12.00001% isMatch=true isPercent=true value=12.00001
string=12.123344% isMatch=true isPercent=true value=12.123344
string=100 isMatch=true isPercent=false value=100
string=100. isMatch=true isPercent=false value=100.
string=100.55252 isMatch=true isPercent=false value=100.55252
string=100.254575 isMatch=true isPercent=false value=100.254575
string=notnum isMatch=false isPercent=false value=0
Upvotes: 2
Reputation: 12496
As Anon has already suggested, you don't really need to use Regular Expressions to solve this problem. What's wrong with:
var number = "12.888%";
if(number[number.length - 1] === '%') {
//processing...
}
Upvotes: 1
Reputation: 15172
jQuery uses JavaScript regular expressions. This is a good starting point https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
For your need, /[0-9]*\.?[0-9]+%/
will be useful.
Upvotes: 5
Reputation: 226
/%$/.test( "35%" ); >> true
/%$/.test( "100" ); >> false
/%$/.test( "35.555%" ); >> true
/%$/.test( "35.555" ); >> false
Take a look at Mozilla Developer Network for some more info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
Upvotes: 2