jQuery parse href for key value pairs
I want to be able to extract a couple of key value pairs (if they exist) from a href. Assume example hrefs like:
http://server/index.pl?foo=bar&baz=123
http://server/index.pl?foo=bar
Basically b开发者_如何学编程az may not exist. Using jQuery I'm capturing this on click function, I'd like to be able to find out what the values are (if they exist).
Thanks
You can use the JQuery URL parser to achieve this. Here is an example where an object of the parameters is returned:
$.url('http://allmarkedup.com?sky=blue&grass=green').param(); // returns { 'sky':'blue', 'grass':'green' }
Something I've used in the past for this is a simple function like this:
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s).replace(/\+/g, " ");
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
Then the $_GET
variable contains everything. $_GET.baz
would return 123
for example. You could also access them like $_GET["baz"]
if you needed to type in strings with spaces.
You can find many solutions on the net, take a look at parseUri, for example.
精彩评论