0

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?

Jon Adams
  • 24,464
  • 18
  • 82
  • 120

3 Answers3

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

alert(n);
  • 2
    Here's a suggestion considering there might be another variable like **mproductid** or if there's a chance that the value might be empty: `var s = (cancelURL.match(/(\?|&)productid=(\d*)/) || ['','',''])[2];` – inhan Feb 14 '12 at 02:44
  • should've been **n = etc.** instead of `s = etc.` sorry for that. – inhan Feb 14 '12 at 03:08
  • @inhan: Good idea. Updated. Only change I made was to make the group a non-capturing group. –  Feb 14 '12 at 03:10
0

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 &.

sazh
  • 1,792
  • 15
  • 20
0

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.

Sina Iravanian
  • 16,011
  • 4
  • 34
  • 45