Home » Jquery » javascript – append url parameter if exists or add if not exists jQuery-Exceptionshub

javascript – append url parameter if exists or add if not exists jQuery-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am creating a filter based on size, color etc. So it is possible to select multiple items. When I click each item it should append to current URL. Please check the below URL,

If parameter not exists in URL

http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White

If parameter exists and selected same color

http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White

If parameter exists and selected multiple colors

http://example.com/category-3?tracker=Q2F0ZWdvcnkgMw&color=White-Black

How to implement the same using jQuery. I have tried using below code,

function setGetParameter(paramName, paramValue) {
    var url = window.location.href;
    var hash = location.hash;
    url = url.replace(hash, '');
    if (url.indexOf(paramName + "=") >= 0) {
        var prefix = url.substring(0, url.indexOf(paramName + "="));
        var suffix = url.substring(url.indexOf(paramName + "="));
        suffix = suffix.substring(suffix.indexOf("=") + 1);
        suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
        url = prefix + paramName + "=" + paramValue + suffix + "-";
    } else {
        if (url.indexOf("?") < 0)
            url += "?" + paramName + "=" + paramValue + "-";
        else
            url += "&" + paramName + "=" + paramValue + "-";
    }
    window.location.href = url + hash;
}

The above code works with single parameter value. For multiple values how to alter the above code.

How to&Answer:

I recommend not using this code at all to build a URL.
Use something like https://medialize.github.io/URI.js/ which happen to have a jQuery plugin.
Why?
Your query parameters here are not encoded, so it could “break” the url. Using a library such as URI.js with a builder to append your query parameters will tackle your issues. Parsing and building URLs is not as trivial as it may seem, so it is better to rely on tested code.

var url = URI(window.location.href); // no need to remove and add the hash back anymore
var queryMap = url.query(true);
if (queryMap[paramName]) {
    // param already exists
    var values = queryMap[paramName].split('-');
    if (!values.includes(paramValue)) {
        // paramValue not found: add it
        values.push(paramValue);
        url.setQuery(paramName, values.join('-'));
    }
} else {
    // param does not exist yet
    url.setQuery(paramName, paramValue);
}

window.location.href = url.toString();