JavaScript
Article

Quick Tip: Get URL Parameters with JavaScript

By Yaphi Berhanu

This article was peer reviewed by Jeff Mott, Andrew Ray, Mev Rael, and Dan Prince. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be!

So you want to get a parameter from a URL? URL parameters (also called query string parameters or URL variables) can have lots of useful data including product info, user preferences, link referrals, and more.

Let’s get started!

Getting URL Parameters

Let’s say you have the following url:

http://example.com/?product=shirt&color=blue&newuser&size=m

Here’s a function to give you all the URL parameters as a neat object:

function getAllUrlParams(url) {

  // get query string from url (optional) or window
  var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

  // we'll store the parameters here
  var obj = {};

  // if query string exists
  if (queryString) {

    // stuff after # is not part of query string, so get rid of it
    queryString = queryString.split('#')[0];

    // split our query string into its component parts
    var arr = queryString.split('&');

    for (var i=0; i<arr.length; i++) {
      // separate the keys and the values
      var a = arr[i].split('=');

      // in case params look like: list[]=thing1&list[]=thing2
      var paramNum = undefined;
      var paramName = a[0].replace(/\[\d*\]/, function(v) {
        paramNum = v.slice(1,-1);
        return '';
      });

      // set parameter value (use 'true' if empty)
      var paramValue = typeof(a[1])==='undefined' ? true : a[1];

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      paramValue = paramValue.toLowerCase();

      // if parameter name already exists
      if (obj[paramName]) {
        // convert value to array (if still string)
        if (typeof obj[paramName] === 'string') {
          obj[paramName] = [obj[paramName]];
        }
        // if no array index number specified...
        if (typeof paramNum === 'undefined') {
          // put the value on the end of the array
          obj[paramName].push(paramValue);
        }
        // if array index number specified...
        else {
          // put the value at that index number
          obj[paramName][paramNum] = paramValue;
        }
      }
      // if param name doesn't exist yet, set it
      else {
        obj[paramName] = paramValue;
      }
    }
  }

  return obj;
}

You’ll see how this works soon, but first, here are some usage examples:

getAllUrlParams().product; // 'shirt'
getAllUrlParams().color; // 'blue'
getAllUrlParams().newuser; // true
getAllUrlParams().nonexistent; // undefined
getAllUrlParams('http://test.com/?a=abc').a; // 'abc'

Things to Know Before Using This Function

  • Our function assumes the parameters are separated by the & character, as indicated in the W3C specifications. However, the URL parameter format in general is not clearly defined, so you occasionally might see ; or &amp; as separators.

  • Our function still works if a parameter doesn’t have an equals sign or if it has an equals sign but no value.

  • The values of duplicate parameters get put into an array.

If you just wanted a function you could drop into your code, you’re done now. If you’d like to understand how the function works, read on.

The following section assumes you know some JavaScript, including functions, objects, and arrays. If you need a refresher, check out the MDN JavaScript reference.

How the Function Works

Overall, the function takes a URL’s query string (the part after the ? and before the #) and spits out the data in a neat object.

First, this line says, if we’ve specified a URL, get everything after the question mark, but otherwise, just use the URL of the window.

var queryString = url ? url.split('?')[1] : window.location.search.slice(1);

Next, we’ll create an object to store our parameters.

var obj = {};

If the query string exists, we’ll start parsing it. First we have to make sure to shave off the part starting from the # since it’s not part of the query string.

queryString = queryString.split('#')[0];

Now we can split the query string into its component parts.

var arr = queryString.split('&');

That will give us an array that looks like this:

['product=shirt', 'color=blue', 'newuser', 'size=m']

Next we’ll loop through this array and split each item into a key and a value, which we’ll soon put into our object.

var a = arr[i].split('=');

We’ll need to deal with duplicate parameters or array parameters like these:

colors=red&colors=green&colors=blue

colors[]=red&colors[]=green&colors[]=blue

colors[0]=red&colors[2]=green&colors[5]=blue

To deal with duplicates and arrays, first we’ll set the parameter’s index number as undefined by default. Then we’ll replace anything in the parameter name that is zero or more digits within square brackets (so [] or [2] or [45]). As we replace, we’ll record if there’s an existing index number.

var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v){
  paramNum = v.slice(1,-1);
  return '';
});

Now we’ll set the parameter value. If there isn’t one, we’ll set it to true to indicate that the parameter name exists. Feel free to change this depending on your use case.

var paramValue = typeof(a[1])==='undefined' ? true : a[1];

Optionally, you can set all parameter names and values to lowercase. That way, you can avoid situations where someone sends traffic to a url with example=TRUE instead of example=true and your script breaks (I’ve seen this happen). However, if your query string needs to be case sensitive, feel free to omit this part:

paramName = paramName.toLowerCase();
paramValue = paramValue.toLowerCase();

If a parameter name already exists at this step in our loop, then we need to put the value in an array like so:

// if parameter name already exists
if (obj[paramName]) {

  // convert value to array (if still string)
  if (typeof obj[paramName] === 'string') {
    obj[paramName] = [obj[paramName]];
  }

  // if no array index number specified...
  if (typeof paramNum === 'undefined') {
    // put the value on the end of the array
    obj[paramName].push(paramValue);
  }

  // if array index number specified...
  else {
    // put the value at that index number
    obj[paramName][paramNum] = paramValue;
  }
}

If the parameter name doesn’t exist yet, we’ll simply create it and set it to the correct value.

obj[paramName] = paramValue;

Finally, we return our object with the parameters and values.

If your URL has any encoded special characters like spaces (encoded as %20), you can also decode them to get the original value like this:

// assume a url parameter of test=a%20space

var original = getAllUrlParams().test; // 'a%20space'
var decoded = decodeURIComponent(original); // 'a space'

Just be careful not to decode something that’s already decoded or else you can get a mistake, especially if percents are involved.

Anyways, congrats! Now you know how to get a URL parameter, and you might have picked up some other tricks along the way.

Conclusion

The code in this article works for the most common use cases where you would get a URL query parameter. If you are working with any edge cases such as uncommon separators or special formatting, then be sure to test and adjust accordingly.

If you want to do more with URLs, there are specific libraries available, such as jQuery URL plugin and Medialize URI.js. Since it’s basically string manipulation, it often makes sense just to use plain JavaScript. Whether you use your own code or go with a library, be sure to check everything and make sure it works for your use cases.

  • Phil Helm

    thanks for the tip

    If you are working in NodeJS then you can parse URLs with the built in modue https://nodejs.org/dist/latest-v4.x/docs/api/url.html

    You can also use that module in the frontend https://github.com/defunctzombie/node-url

  • zema

    there is a way much easier))

    https://www.npmjs.com/package/qs
    npm install qs –save
    var qs = require(‘qs’);
    var params = qs.parse(location.search.replace(/^?/, ”));

  • https://www.comandeer.pl/ Comandeer

    It’s worth noting that in Blink and Gecko we have URLSearchParams which is a standard way to deal with URL parameters.

  • http://simplestepscode.com/ Yaphi Berhanu

    If you’re looking for a shorter function and your URL parameters have a basic structure, you can use something like this as well:

    function getUrlParameter(param){
    var pattern = new RegExp(‘[?&]’+param+'((=([^&]*))|(?=(&|$)))’,’i’);
    var m = window.location.search.match(pattern);
    return m && ( typeof(m[3])===’undefined’ ? ” : m[3] );
    }

    Example url to test on:
    http://example.com/?product=shirt&color=blue&newuser&size=m

    Example usage:
    getUrlParameter(shirt);

    This function isn’t quite as robust (which is why I didn’t put it in the article), but it can also get the job done depending on your needs.

  • Dustin Wehr

    Thanks brother

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.