Reputation: 3
I'm writing a Javascript function. I need to grab the number 228 from the following variable
var cancelURL = "artGallery.cgi?productid=228&key=photo&resultsC=20";
Can someone show me how to write the regex pattern to search for a number in a value pair?
Upvotes: 0
Views: 129
Reputation: 16286
Use the following regexp to match the whole url, and then within the matched content look for groups named par
and value
, which matches the parameter and the corresponding value after =
respectively:
[^?]+\?(\&?(?<par>\w+)=(?<value>\w+))+
This is a general solution, but solves the specific problem of looking for a productid
parameter also.
Upvotes: 0
Reputation:
var n = (cancelURL.match(/(?:\?|&)productid=(\d+)/) || [null,null])[1];
alert(n);
Upvotes: 1
Reputation: 1832
If you're always looking for the productid
, you can use /productid=([^&]*)/i
as your regex. That will grab everything after the =
and before the next &
.
Upvotes: 0