Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 25, 2014 00:34
Show Gist options
  • Save bennadel/9752591 to your computer and use it in GitHub Desktop.
Save bennadel/9752591 to your computer and use it in GitHub Desktop.
Ask Ben: Getting Query String Values In JavaScript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Parsing URL Query String In Javascript</title>
<script type="text/javascript">
// Build an empty URL structure in which we will store
// the individual query values by key.
var objURL = new Object();
// Use the String::replace method to iterate over each
// name-value pair in the query string. Location.search
// gives us the query string (if it exists).
window.location.search.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
// For each matched query string pair, add that
// pair to the URL struct using the pre-equals
// value as the key.
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
</script>
</head>
<body>
<p>
<script type="text/javascript">
// Loop over the URL values that we collected.
for (var strKey in objURL){
// Output the key to the document.
document.write(
"<strong>" + strKey + ":</strong> "
);
// Output the value stored at that key.
document.write(
objURL[ strKey ] + "<br />"
);
}
</script>
</p>
<p>
<strong>Database:</strong>
<span id="database"></span>
</p>
<script type="text/javascript">
// Now that the most of the document is loaded, we
// can reach into the DOM and set values on specific
// node elements. Let's set the Database node.
var objNode = document.getElementById( "database" );
// Check to make sure we have a valid node and that
// our URL does indeed contain the proper variable.
if (objNode && objURL[ "i" ]){
// Set the inner HTML to reflect the value of
// the database that was sent in the URL.
objNode.innerHTML = objURL[ "i" ];
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment