use like this:
getQueryVariable("foo")
To get variables in urls eg:
http://foo.com/index.html?foo=bar
If you want to support arrays, check the version by @atk below:
use like this:
getQueryVariable("foo")
To get variables in urls eg:
http://foo.com/index.html?foo=bar
If you want to support arrays, check the version by @atk below:
function(a){ | |
return RegExp("[&?]"+a+"=([^&]+)").exec(location)[1] | |
} | |
//searches the url (location) | |
//finds the text after a "&" or a "?" followed by the variable name, followed by a "=" | |
//and before another "&" |
{ | |
"name": "getQueryVariable", | |
"description": "Get variables in urls", | |
"keywords": [ | |
"url", | |
"query", | |
"string", | |
"variable", | |
"get" | |
] | |
} |
@atk |
@williammalo: we live and learn :-) |
What about using split with regex? |
The original code did, but exec is much smaller. |
What about supporting array values (e.g. |
@FarSeeing |
@williammalo // location = 'http://example.com?a=1&b[]=2&b[]=3'
getQueryVariable = function(a){return RegExp("[&?]"+a+"=([^&]+)").exec(location)[1]}
getQueryVariable( 'a' ); // "1", correct
getQueryVariable( 'b' ); // TypeError: RegExp("[&?]" + a + "=([^&]+)").exec(txt) is null
getQueryVariable( 'b[]' ); // TypeError: RegExp("[&?]" + a + "=([^&]+)").exec(txt) is null |
A version which supports array: |
Those TypeErrors can be caught with a (...||0)[1] construct as in my proposal. |
@tsaniel |
Only 1 char longer: |
@atk |
If you have an anchor on url like param=value#anchor it returns the value like value#anchor, you just need to add one more byte to the code to works =D function url(a){for(var b=[],c,d=eval('/[&?]'+a+'([])?=([^&^#]+)/g');c=d.exec(location);)b.push(c[2]);return b} |
This comment has been minimized.
&|\\?
will not work properly, as it will match either "&" or "?[identifier=]", therefore returning the whole [identifier]=[value] string if it is preceded by "&". A working version would be:function(a){return(RegExp('[&?]'+a+'=([^&;]+)').exec(location)||0)[1]}