Page Parameters from JavaScript

July 6, 2010

Here's how to get hold of page parameters from JavaScript code. This involves grabbing the whole URL and then looking through it for the parameters.

Code

This example code can be called with a single parameter called message, i.e. http://localhost:8000/test.html?message=drumcoder. The value of the message parameter is then included in the HTML shown to the user.

<!DOCTYPE html>
<html>
<head>
<title>Parameter Test</title>
<script type="text/javascript">

function getParameter(pName)
{
  lName = pName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var lRegexS = "[\\?&]"+lName+"=([^&#]*)";
  var lRegex = new RegExp( lRegexS );
  var lResults = lRegex.exec( window.location.href );
  if( lResults == null )
    return "";
  else
    return lResults[1];
}
</script>
</head>
<body>
<h1>Parameter Test</h1>
<p>Message = <span id="message"><script type="text/javascript">document.write(getParameter("message"));</script></span></p>
</body>
</html>

UPDATE

A simpler mechanism for this is as follows:

function getUrlVars() {
  var lVariables = {};
  var lParts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    lVariables[key] = value;
  });
  return lVariables;
}

You can now get values as follows:

var lFirst = getUrlVars()["id"];
var lSecond = getUrlVars()["page"];

References