Reputation: 1
I need to use a regular expression in javascript to match certain text in a url.
Here is an example:
"qty1=0&qty2=0&qty3=0&"
I want to match the text(number) that comes after the '=' and before the '&' whenever the word 'qty' appears in the string. The text(number) will be subject to change every time the url is generated, so I want to match whatever the new text(number) may be.
What regular expression could I use to solve this?
Any help would be appreciated!
Upvotes: 0
Views: 214
Reputation: 11779
var queryStr = "qty1=0&qty2=0&qty3=0";
var regex = /qty(\d+)=(\d+)/g;
var match = regex.exec(queryStr);
while(match != null){
var numBeforeEquals = match[1];
var numAfterEquals = match[2];
// do your comparison, for example, if it's > 0:
if(numAfterEquals > 0){
// do something
}
match = regex.exec(queryStr);
}
Note the /g at the end of the regex, in some javascript implementations you will end up with an infinite loop without it.
Upvotes: 1
Reputation: 5731
Here is an alternative solution (inside a working URL). I call it alternative because I'm using the parts of the expression twice, I think it could be optimized.
var breakdown = "http://local/?wtf=omg&qty12=a&qty2=b&qty3=4&test=5".match(/qty[0-9]{0,9999}(.*?)&/ig);
for(var i in breakdown) {
var v = breakdown[i].match(/qty[0-9]{0,9999}\=(.*?)&/i)[1];
if(v == 4 || v == "a") {
alert("Found '"+v+"'!")
}
}
Working Example: http://jsfiddle.net/MattLo/FxDyg/
Upvotes: 0
Reputation: 4932
try this
var regex = /qty[\d]+=(\d+)/g,
text = "qty1=5&qty2=7&qty3=8&";
while(match = regex.exec(text)) {
console.log(match[1]);
}
@ggreiner missing +
in \d
that make the script above does not work with number greather than 9 e.g. 10, 11
Upvotes: 0