Tuesday, November 24, 2009

Using URL parameters in Javascript

This is a simple function to parse parameters out of a URL and return them as properties of an object:

<script type="text/javascript">
// example URL: http://example.com/script.html?foo=hello+world&bar=goodbye

// function to parse the URL
function getParams (url) {

// split url into host/path and args, then split args into an array
var argstr = url.split("?")[1] || '';
var args = argstr.split("&");

var params = new Object;

// args will have len=1 even if split() returned empty, so fix that
var length = args[0] ? args.length : 0;

// loop args and load into object properties
for ( var i=0; i<length; i++ ) {
var p = args[i].split("=");
params[p[0]] = unescape(p[1]).replace(/\+/g, ' ');
}

return(params);
}

// send it our URL
var params = getParams(window.location.href);

// use the parameters
document.write("foo = " + params.foo + "<br>");
document.write("bar = " + params.bar + "<br>");

// output is:
// foo = hello world
// bar = goodbye
</script>

No comments:

Post a Comment