After stumbling through a few blog and stack overflow posts, I finally landed on an article by David Walsh to find the best way to parse a website URL with Query String parameters. In his article he refers to the use of a URLSearchParams JavaScript object that is natively available in modern browser.

The URLSearchParams interface defines utility methods to work with the query string of a URL.

To new up a new URLSearchParams object, you just pass the window.location.search string and it will handle the parsing automatically. You now have functions off the urlParams object to .has(“piece”), .get(“something”)

var urlParams = new URLSearchParams(window.location.search);

HOWEVER, this function is not supported across all browser at this time. CanIUse.com shows there are a few holes, with the biggest hole being IE 11. If you can confidently say your users are not using IE then maybe you could use this, and it looks like 85% of internet users have this functionality available according to caniuse. That 15% is enough of a gap to lead me to hesitate to use this solution. There are polyfills for this missing function here. Alternatively, I choose to follow David’s lead and use a function borrowed from AFrame VR.

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

Here’s a link to David’s original blog post.

Get Query String Parameters with JavaScript