kelvinangular
kelvinangular

Reputation: 3

How to match a number in an url value pair

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

Answers (3)

Sina Iravanian
Sina Iravanian

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

user1106925
user1106925

Reputation:

var n = (cancelURL.match(/(?:\?|&)productid=(\d+)/) || [null,null])[1];

alert(n);

Upvotes: 1

sazh
sazh

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

Related Questions