Get Query String Parameters with JavaScript

As the internet took lift off, query string parameters have been incredibly useful on the server-side, but it wasn’t until AJAX-driven web applications were common that we depended too much on them on the client-side. With the History API, we not only grab parameter values but also dynamically modify them, so these parameters play a major role outside the initial page load. Getting the Query String in JavaScript is quite simple and easy to implement.

We were always able to get the full Query String via the property window.location.search:

console.log(window.location.search);
// "?post=1234&action=edit"

But there has to be a better way to get values in an environment of setters, getters, and JSON than to parsing a script, right? There is a better way, despite years of hideous string parsing:

URLSearchParams Let’s look at how we can get values from the position using this new API!

// Assuming "?post=1234&action=edit"
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?post=1234&action=edit&active=1"

There are some familiar object methods provided by URLSearchParams like keys(), values(), and entries():

var keys = urlParams.keys();

for(key of keys) {
    console.log(key);
}

// post
// action

var entries = urlParams.entries();

for(pair of entries) {
    console.log(pair[0], pair[1]);
}

URLSearchParams reminds me of the classList API — very basic yet very helpful methods.

 

JavaScript Fallback

 

While it is ideal for URLSearchParams, not all browsers support that API. There is a polyfill available, but if you want a tiny function to parse the basic query string, the following is a function stolen from the A-Frame VR toolkit that parses the query string to get the value of the key that you want:

function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);

    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

You can get individual parameter values using the method above:

getUrlParameter('post'); // "1234"
getUrlParameter('action'); // "edit"

So, isn’t it very easy to get url parameters in JavaScript?

 

Love this role anyway — you will find yourself in need of it more than you thought!

Leave a Reply