Javascript – Get URL Query String

We can obtain the URL query string with the following Javascript function.

function GET() {
  var data = [];
  var param;
  for(x = 0; x < arguments.length; ++x) {
    param = location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")));
    if (param == null) {
      data.push("");
    } else {
      data.push(param[1]);
    }
  }
  return data;
}	

 

Try the following example.

<html>
  <head>
    <script type="text/javascript">
      // Reference: http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
      function GET() {
        var data = [];
        var param;
        for(x = 0; x < arguments.length; ++x) {
          param = location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")));
          if (param == null) {
            data.push("");
          } else {
            data.push(param[1]);
          }
        }
        return data;
      }			
    </script>
  </head>
  <body>
    <h1>Hello World</h1>
    <script type="text/javascript">
      // example: http://www.example.com/index.html?name=ykyuen&age=27
      alert(GET('name'));        // ykyuen
      alert(GET('age'));         // 27
      alert(GET('name', 'age')); // ykyuen,27
    </script>
  </body>
<html>

 

The code above is originated from the suggestion by Jet @ Get query string values in JavaScript. i have modified it a bit so it won’t crash if the query string was not found. Thanks Jet.

Done =)

Reference: Get query string values in JavaScript

About these ads

3 thoughts on “Javascript – Get URL Query String”

      1. Hey ykyuen,

        After some testing several times. It will return whats in the QueryString, but it seems to be cutting off the numbers. I have about an 8 digit ID number that I’m trying to retrieve. It either returns 1, 2, 3, or 5 digits, but never the entire 8.

        Any ideas why this might be occurring?

        Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s