views:

289

answers:

5

If I am on a page such at

http://somesite.com/somepage.php?param1=asf

in the javascript of that page, I would like to set a variable to the value of the paramater in the GET part of the url

so in javascript:

<script ...>
   param1var = ...   // ... would be replaced with the code to get asdf from url
</script>

What would "..." be?

A: 

Using jquery? I've used this before: http://projects.allmarkedup.com/jquery_url_parser/ and it worked pretty well.

marcc
Unfortunately not (not my choice).
RobKohr
+10  A: 

Here's some sample code for that.

<script>
var param1var = getQueryVariable("param1");

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  alert('Query Variable ' + variable + ' not found');
}
</script>
Jose Basilio
Perfect, thanks José!
RobKohr
A: 

This looked ok:

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];
}

From http://www.netlobo.com/url_query_string_javascript.html

agilefall
+1  A: 

From my programming archive:

function querystring(key) {
   var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
   var r=[], m;
   while ((m=re.exec(document.location.search)) != null) r[r.length]=m[1];
   return r;
}

If the value doesn't exist, an empty array is returned.
If the value exists, an array is return that has one item, the value.
If several values with the name exists, an array containing each value is returned.

Examples:

var param1var = querystring("param1")[0];

document.write(querystring("name"));

if (querystring('id')=='42') alert('We apoligize for the inconvenience.');

if (querystring('button').length>0) alert(querystring('info'));
Guffa
A: 

You can get the "search" part of the location object - and then parse it out.

var matches = /param1=([^&#=]*)/.exec(window.location.search);
var param1 = matches[1];
gnarf