How can I add or update a query string parameter?

后端 未结 27 2873
别那么骄傲
别那么骄傲 2020-11-22 02:35

With javascript how can I add a query string parameter to the url if not present or if it present, update the current value? I am using jquery for my client side development

27条回答
  •  时光说笑
    2020-11-22 03:22

    Based on the answer @ellemayo gave, I came up with the following solution that allows for disabling of the hash tag if desired:

    function updateQueryString(key, value, options) {
        if (!options) options = {};
    
        var url = options.url || location.href;
        var re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"), hash;
    
        hash = url.split('#');
        url = hash[0];
        if (re.test(url)) {
            if (typeof value !== 'undefined' && value !== null) {
                url = url.replace(re, '$1' + key + "=" + value + '$2$3');
            } else {
                url = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
            }
        } else if (typeof value !== 'undefined' && value !== null) {
            var separator = url.indexOf('?') !== -1 ? '&' : '?';
            url = url + separator + key + '=' + value;
        }
    
        if ((typeof options.hash === 'undefined' || options.hash) &&
            typeof hash[1] !== 'undefined' && hash[1] !== null)
            url += '#' + hash[1];
        return url;
    }
    

    Call it like this:

    updateQueryString('foo', 'bar', {
        url: 'http://my.example.com#hash',
        hash: false
    });
    

    Results in:

    http://my.example.com?foo=bar
    

提交回复
热议问题