0

Possible Duplicate:
Get query string values in JavaScript

If one submits a GET form, the resulting address will look like www.example.com/stuff?param1=stuff&param2=morestuff. I know how to read/set the value of a form field on a page, but how do I read submissions from the previous page (in the URL) with JavaScript? I guess I could take the url and split() it, to get the parameters, but is there any quicker/simpler way to read param1 (just an example)?

Note: this is not a duplicate of this, since that question is about how to do it in PHP.

Community
  • 1
  • 1
Bluefire
  • 13,519
  • 24
  • 74
  • 118

4 Answers4

0

No, there's no simple way to do that.

Use something like this:

var qstring = {}, src = location.search.substring(1).split("&");
for (var i = 0; i < src.length; i++) {
    var parts = src[i].split("=");
    qstring[unescape(parts[0])] = unescape(parts.slice(1).join("="));
}

Now the object qstring is a key/value map of the query string. Keep in mind that values with the same key are overwritten, so you may want to store them in an indexed array instead of an associative array.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
0
function getQuerystring(key)

{
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,\\\]);

 var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");

 var qs = regex.exec(window.location.href);

 if(qs != null)
     return(qs[1]);
 else
     return("");

}
Raab
  • 34,778
  • 4
  • 50
  • 65
  • I'm impressed how you and Iwo gave almost the same answer. Basically the same function that doesn't use `location.search`. – MaxArt Jul 05 '12 at 17:24
0

I think this topic is answer to your question.

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

You can try also this one

Community
  • 1
  • 1
Iwo Kucharski
  • 3,735
  • 3
  • 50
  • 66
0
Nadav S.
  • 2,429
  • 2
  • 24
  • 38
  • It's like killing a mosquito with a barrel gun... – MaxArt Jul 05 '12 at 17:22
  • @MaxArt Excuse me, maybe I'm stupid. But I don't understand?!! – Nadav S. Jul 05 '12 at 17:25
  • That plugin does a lot more than parsing the query string. So Bluefire would load the whole jQuery framework, plus that plugin, for a task of a bunch of lines of code. Heavy. – MaxArt Jul 05 '12 at 17:30
  • @MaxArt you know what, maybe your'e right. I will edit my answer, there is also a tiny library that doesn't use jQuery. Thanks for that – Nadav S. Jul 05 '12 at 17:32