I’ve said it before, but not quite so explicitly – it’s easiest to get query string parameters with a regular expression. I keep seeing big JavaScript functions looping through and splitting the parameters up, and that might be fine if you want to store those and use them repeatedly – but if not, regexes are your friend.
This function will return the value of a parameter. If the parameter requested isn’t in the query string, it returns null.If the parameter doesn’t have a value (e.g. debug
in ...&debug&...
) it returns an empty string.
function GetQueryParam(parameter){
var p = escape(unescape(parameter));
var regex = new RegExp("[?&]" + p + "(?:=([^&]*))?","i");
var match = regex.exec(window.location.search);
var value = null;
if( match != null ){
value = match[1];
}
return value;
}
I would dearly love to see this working. I am trying to grab the keyword value from a search result in order to build some dynamic links.
e.g. k=John
Try a people search.
Thanks ! Yes this is an older blog page, but it was there when I needed it on top of google.
Here the adapted flash AS3 code to obtain a query variable in case someone needs it, as I did 🙂
public static function browserSearchParam(id:String):String
{
if (ExternalInterface.available) {
var queryString:String = ExternalInterface.call(“window.location.search.toString”);
var p = id;
var regex:RegExp = new RegExp(“[?&]” + p + “(?:=([^&]*))?”,”i”);
var match:Array = regex.exec(queryString);
var value:String = null;
if( match && match.length){ value = match[1]; }
return value;
}
return null;
}