Elegant way of retrieving query string parameter
I am retrieving one query string parameter, and for that my code is
<a href="Default2.aspx?Id=1&status=pending&year=2010">Click me</a>
Now I want to retrieve "status=pending" and for that I am doing
var qString = window.location.search.substring(1);
var Keys = qString .split('&');
alert(Keys[1]);
This works fine, but I am hard-c开发者_Go百科oding [1] here. is there any elegent way of doing this without hard-coding?
I'd use a regular expression such as:
status=([a-zA-Z])+
This will retrieve only what the status is. If you already know the variable is always called status, but don't know what the value is, this is the right way to go.
To use it, you'd have to do something like this:
var qString = window.location.search.substring(1);
qString.match(/status=([a-zA-Z])+/);
Hope it helps
you can also consider a dedicated url/querystring parser, like this one
Try this out the easiest and best way without hard coding the index
params = location.search;
getParam = function(arg) { if (params.indexOf(arg) >= 0) { var pntr = params.indexOf(arg) + arg.length + 1; if (params.indexOf("&", pntr) >= 0) { return params.substring(pntr, params.indexOf("&", pntr)); } else { return params.substring(pntr, params.length); } } else { return null; } }
So you'd end up with something like:
?status=someValue
var val = getParam("status");
val would be "somevalue"
精彩评论