james kampel james kampel - 1 month ago 11
Javascript Question

How to edit this function and make it set URL parameter if it doesn't exist

The following function is designed to replace a variable in the URL.

It works, but I want to make it so that if you pass in a variable that doesn't exist in the URL, it will add it to the URL.

window.setUrlParameter = function(param, value) {
const regExp = new RegExp(param + "(.+?)(&|$)", "g");
const newUrl = window.location.href.replace(regExp, param + "=" + value + "$2");
window.history.pushState("", "", newUrl);
}


There is the function. It takes the param name that you want to replace, and the value you want to set.

As I stated earlier, I want it to be able to not only replace variables, but set them as well.

Thanks!

Answer Source

This function should also be faster than using a regex, modified from this answer.

(The arrow function is just ES6 syntax, you can use normal functions if you want too)

window.setUrlParameter = (param, value) => {
    var url = window.location.href;
    var hash = location.hash;
    url = url.replace(hash, '');
    if (url.indexOf(param + "=") >= 0)
    {
        var prefix = url.substring(0, url.indexOf(param));
        var suffix = url.substring(url.indexOf(param));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + param + "=" + value + suffix;
    }
    else
    {
        if (url.indexOf("?") < 0)
            url += "?" + param + "=" + value;
        else
            url += "&" + param + "=" + value;
    }
    window.history.pushState(null, null, url + hash);
}