Thursday, February 11, 2010

Get Request Param Values in Javascript

The following should get any request parameter from the URL, escaping all characters used in regular expressions:
function getReqParam(name)
{
  var regexpstr = "[\\?&]"+escapeRegExp(name)+"=([^&#]*)";
  var arr = new RegExp(regexpstr).exec(window.location.href);
  if(arr == null) return null;
  return arr[1];
}

function escapeRegExp(value) {
  return value.replace(/\\/g,"\\\\").replace(/\//g,"\\\/").replace(/\./g,"\\\.").replace(/\*/g,"\\\*").replace(/\+/g,"\\\+").replace(/\?/g,"\\\?").replace(/\|/g,"\\\|").replace(/\(/g,"\\\(").replace(/\)/g,"\\\)").replace(/\[/g,"\\\[").replace(/\]/g,"\\\]").replace(/\{/g,"\\\{").replace(/\}/g,"\\\}");
}
Here is a example test HTML that you can use to see how it works by specifying the request parameter as the target (like ?someparam=somevalue#someparam), just for the heck of it.
<html>
<head><title>test</title></head>
<body>
<script language="javascript" type="text/javascript" defer>
<!--
function getReqParam(name)
{
  var regexpstr = "[\\?&]"+escapeRegExp(name)+"=([^&#]*)";
  var arr = new RegExp(regexpstr).exec(window.location.href);
  if(arr == null) return null;
  return arr[1];
}

function escapeRegExp(value) {
  return value.replace(/\\/g,"\\\\").replace(/\//g,"\\\/").replace(/\./g,"\\\.").replace(/\*/g,"\\\*").replace(/\+/g,"\\\+").replace(/\?/g,"\\\?").replace(/\|/g,"\\\|").replace(/\(/g,"\\\(").replace(/\)/g,"\\\)").replace(/\[/g,"\\\[").replace(/\]/g,"\\\]").replace(/\{/g,"\\\{").replace(/\}/g,"\\\}");
}

window.location.href="?\/.*+?|(){}[]{}=asdf#\/.*+?|(){}[]{}"
if (window.location.hash == null || window.location.hash.length < 2) {
  document.write("modify the url to specify req param and hash (target) is the req param name")
} else {
  document.write( "request param name '" + window.location.hash + "'=" + getReqParam(window.location.hash.substr(1)) + "<br/>");
}
-->
</script>
</body></html>
I didn't find any other examples that allowed all of the characters ""/.*+?|(){}[]{}"" in the request parameter name, even though the likelihood of that is low for most applications.

No comments: