Search code examples
javascriptregexfirefox-addon-sdk

RegEx: Extract GET variable from URL


RegExp gurus, heed my call!

This is probably super simple, but I've painted myself in a mental corner.

Taking a regular URL, split after the ?, which gives a string like variable=val&interesting=something&notinteresting=somethingelse I want to extract the value of interesting.

The name of the variable I'm interested in can be a substring of another variable. So the match should be

  • either beginning of string or "&" character
  • followed by "interesting="
  • followed by the string I want to capture
  • followed by either another "&" or end of string

I tried something along the lines of [\^&]interesting=(.*)[&$] but I got nothing...

Update This is to be run in a Firefox addon on every get request, meaning that jQuery is not available and if possible I would like to avoid the extra string manipulation caused by writing a function.

To me this feels like a generic "extract part of a string with regex" but maybe I'm wrong (RegEx clearly isn't my strong side)


Solution

  • simple solution

    var arr = "variable=val&interesting=something&notinteresting=somethingelse".split("&");
    for(i in arr) {
    var splits = arr[i].split("=");
    if(splits[0]=="interesting") alert(splits[1]);
    }
    

    also single line match

    "variable=val&interesting=something&notinteresting=somethingelse".match(/(?:[&]|^)interesting=((?:[^&]|$)+)/)[1]