简体   繁体   中英

using javascript regex to capture text in a url

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!

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.

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/

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 eg 10, 11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM