0

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-coding [1] here. is there any elegent way of doing this without hard-coding?

Wondering
  • 4,950
  • 22
  • 71
  • 90

3 Answers3

2

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

Marcos Placona
  • 21,468
  • 11
  • 68
  • 93
1

you can also consider a dedicated url/querystring parser, like this one

user187291
  • 53,363
  • 19
  • 95
  • 127
  • Or try Adam Vandenberg's implementation (http://adamv.com/dev/javascript/querystring) that doesn't depend on jQuery. – jou Mar 08 '10 at 09:50
0

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"

Ravi Vanapalli
  • 9,805
  • 3
  • 33
  • 43