tags:

views:

660

answers:

4

If I had a URL such as

http://localhost/search.php?year=2008

How would I write a JavaScript function to grab the variable year and see if it contains anything?

I know it can be done with location.search but I can’t figure out how it grabs parameters.

thanks

+2  A: 
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];
}
var year = gup("year"); // returns "2008"
Luca Matteis
You should use `window.location.search` instead of `window.location.href`. This would simplify your expressions not having to check for the hash or query markers
Justin Johnson
It would be a good idea to **escape all regex meta characters** in "name" before creating a regex off of it.
kangax
+1  A: 

A non-regex approach, you can simply split by the character '&' and iterate through the key/value pair:

function getParameter(paramName) {
  var searchString = window.location.search.substring(1),
      i, val, params = searchString.split("&");

  for (i=0;i<params.length;i++) {
    val = params[i].split("=");
    if (val[0] == paramName) {
      return val[1];
    }
  }
  return null;
}
CMS
Isn't `val` a global in there?
Luca Matteis
@sarmenhb: You can do: var year=getParameter("year"); if (year){ document.location.href='page.php?year='+year;}
CMS
@Luca Matteis: No, val is not a global in there. It's defined as a local var in var searchString, i, val, ...
Alex
A: 

The following uses regular expressions and searches only on the query string portion of the URL.

Most importantly, this method supports normal and array parameters as in http://localhost/?fiz=zip&amp;foo[]=!!=&amp;bar=7890#hashhashhash

function getQueryParam(param) {
    var result =  window.location.search.match(
        new RegExp("(\\?|&)" + param + "(\\[\\])?=([^&]*)")
    );

    return result ? result[3] : false;
}

console.log(getQueryParam("fiz"));
console.log(getQueryParam("foo"));
console.log(getQueryParam("bar"));
console.log(getQueryParam("zxcv"));

Output:

zip
!!=
7890
false
Justin Johnson
+1  A: 

My favorite way for getting URL params is this approach:

parseQueryString = function() {

    var str = window.location.search;
    var objURL = {};

    str.replace(
     new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
     function( $0, $1, $2, $3 ){
      objURL[ $1 ] = $3;
     }
    );
    return objURL;
};

//Example how to use it: 
var params = parseQueryString();
alert(params["foo"]);

Cheers Alex

Alex