Get Query Params in IE 11

Viewed 2876

This function errors out in IE 11 but works with other browsers. I expect params to be something like params = {user: 123} if URL is http://example.com/?user=123.

let params = {};
window.location.href.replace(
    /[?&]+([^=&]+)=([^&]*)/gi,
    (_, key, value) => (params[key] = value)
); 
2 Answers

Because IE 11 does not support the arrow function syntax, you have to[1] replace that code with the equivalent that has an explicit callback function

var params = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
    function(_, key, value) {
        return params[key] = value;
    });

As griest mentions in a comment, to be safe you should use decodeURIComponent on the href, so that line becomes

decodeURIComponent(window.location.href).replace(/..etc../,

[1] "have to", unless you are in the fortunate position of just declaring that you don't support Internet Explorer.

Try this one:

var params = new URLSearchParams(url)
params.get(name)

Related