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

Let’s get started!

Getting a URL Parameter

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('=');

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

      // (optional) keep case consistent
      paramName = paramName.toLowerCase();
      if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();

      // if the paramName ends with square brackets, e.g. colors[] or colors[2]
      if (paramName.match(/[(d+)?]$/)) {

        // create key if it doesn't exist
        var key = paramName.replace(/[(d+)?]/, '');
        if (!obj[key]) obj[key] = [];

        // if it's an indexed array e.g. colors[2]
        if (paramName.match(/[d+]$/)) {
          // get the index value and add the entry at the appropriate position
          var index = /[(d+)]/.exec(paramName)[1];
          obj[key][index] = paramValue;
        } else {
          // otherwise add the value to the end of the array
          obj[key].push(paramValue);
        }
      } else {
        // we're dealing with a string
        if (!obj[paramName]) {
          // if it doesn't exist, create property
          obj[paramName] = paramValue;
        } else if (obj[paramName] && typeof obj[paramName] === 'string'){
          // if property does exist and it's a string, convert it to an array
          obj[paramName] = [obj[paramName]];
          obj[paramName].push(paramValue);
        } else {
          // otherwise add the property
          obj[paramName].push(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'

And a demo for you to play around with.

See the Pen rQGWpP by (@SitePoint) on CodePen.

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 , 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('=');

Let’s assign the key and a value to individual variables. If there isn’t a parameter value, we’ll set it to true to indicate that the parameter name exists. Feel free to change this depending on your use case:

var paramName = a[0];
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();
if (typeof paramValue === 'string') paramValue = paramValue.toLowerCase();

Next we need to deal with the various types of input we can receive in paramName. This could be an indexed array, a non-indexed array, or a regular string.

If it’s an indexed array, we want the corresponding paramValue to be an array, with the value inserted at the correct position. If it’s a non-indexed array, we want the corresponding paramValue to be an array with the element pushed on to it. If it’s a string, we want to create a regular property on the object and assign the paramValue to it, unless the property already exists, in which case we want to convert the existing paramValue to an array and push the incoming paramValue on to that.

To illustrate this, here’s some sample input, with the output we would expect:

getAllUrlParams('http://example.com/?colors[0]=red&colors[2]=green&colors[6]=blue');
// { "colors": [ "red", null, "green", null, null, null, "blue" ] }

getAllUrlParams('http://example.com/?colors[]=red&colors[]=green&colors[]=blue');
// { "colors": [ "red", "green", "blue" ] }

getAllUrlParams('http://example.com/?colors=red&colors=green&colors=blue');
// { "colors": [ "red", "green", "blue" ] }

getAllUrlParams('http://example.com/?product=shirt&color=blue&newuser&size=m');
// { "product": "shirt", "color": "blue", "newuser": true, "size": "m" }

And here’s the code to implement the functionality:

if (paramName.match(/[(d+)?]$/)) {
  var key = paramName.replace(/[(d+)?]/, '');
  if (!obj[key]) obj[key] = [];

  if (paramName.match(/[d+]$/)) {
    var index = /[(d+)]/.exec(paramName)[1];
    obj[key][index] = paramValue;
  } else {
    obj[key].push(paramValue);
  }
} else {
  if (!obj[paramName]) {
    obj[paramName] = paramValue;
  } else if (obj[paramName] && typeof obj[paramName] === 'string'){
    obj[paramName] = [obj[paramName]];
    obj[paramName].push(paramValue);
  } else {
    obj[paramName].push(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.

An Alternative for Modern Browsers

If you don’t need to support legacy browsers, you might like to look at the URLSearchParams interface, which defines utility methods to work with the query string of a URL:

// URL is http://example.com/?product=shirt&color=blue&newuser&size=m
const urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('product')); // true
console.log(urlParams.get('product')); // "shirt"

It also provides familiar Object methods like keys(), values(), and entries().

Conclusion

The code in this article works for the most common use cases where you would get a URL query parameter. If you’re 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.


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!



Source link https://www.sitepoint.com/get-url-parameters-with-javascript/

LEAVE A REPLY

Please enter your comment!
Please enter your name here