BanisterMurray of Spaghetti
8/18/2017 - 7:29 PM

QueryString manipulation via jQuery

QueryString manipulation via jQuery

            jQuery.extend({
                getUrlVars: function () {
                    var vars = [], hash;
                    if (window.location.href.indexOf('?') == -1) {
                        return vars;
                    }
                    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                    for (var i = 0; i < hashes.length; i++) {
                        hash = hashes[i].split('=');
                        vars.push(hash[0]);
                        vars[hash[0]] = hash[1];
                    }
                    return vars;
                },
                getUrlVar: function (name) {
                    return jQuery.getUrlVars()[name];
                },
                setURLVars: function (vars) {
                    var qString = "";
                    for (var i = 0; i < vars.length; i++) {
                        var key = vars[i];
                        var value = vars[vars[i]];
                            if (qString === "") {
                                qString = "?" + key + "=" + value;
                            } else {
                                qString = qString + "&" + key + "=" + value;
                            }                        
                    }
                    window.history.pushState(null, document.title, window.location.origin + window.location.pathname + qString);
                },
                setUrlVar: function (name, value) {
                    var vars = jQuery.getUrlVars();
                    if (vars[name] == undefined) {
                        vars.push(name);
                    }
                    vars[name] = value;
                    jQuery.setURLVars(vars);
                },
            });