How can I add or update a query string parameter?

后端 未结 27 3378
别那么骄傲
别那么骄傲 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:17

    Code that appends a list of parameters to an existing url using ES6 and jQuery:

    class UrlBuilder {
        static appendParametersToUrl(baseUrl, listOfParams) {
    
            if (jQuery.isEmptyObject(listOfParams)) {
                return baseUrl;
            }
    
            const newParams = jQuery.param(listOfParams);
    
            let partsWithHash = baseUrl.split('#');
            let partsWithParams = partsWithHash[0].split('?');
    
            let previousParams = '?' + ((partsWithParams.length === 2) ? partsWithParams[1] + '&' : '');
            let previousHash = (partsWithHash.length === 2) ? '#' + partsWithHash[1] : '';
    
            return partsWithParams[0] + previousParams + newParams + previousHash;
        }
    }
    

    Where listOfParams is like

    const listOfParams = {
        'name_1': 'value_1',
        'name_2': 'value_2',
        'name_N': 'value_N',
    };
    

    Example of Usage:

        UrlBuilder.appendParametersToUrl(urlBase, listOfParams);
    

    Fast tests:

        url = 'http://hello.world';
        console.log('=> ', UrlParameters.appendParametersToUrl(url, null));
        // Output:  http://hello.world
    
        url = 'http://hello.world#h1';
        console.log('=> ', UrlParameters.appendParametersToUrl(url, null));
        // Output:  http://hello.world#h1
    
        url = 'http://hello.world';
        params = {'p1': 'v1', 'p2': 'v2'};
        console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
        // Output: http://hello.world?p1=v1&p2=v2
    
        url = 'http://hello.world?p0=v0';
        params = {'p1': 'v1', 'p2': 'v2'};
        console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
        // Output: http://hello.world?p0=v0&p1=v1&p2=v2
    
        url = 'http://hello.world#h1';
        params = {'p1': 'v1', 'p2': 'v2'};
        console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
       // Output: http://hello.world?p1=v1&p2=v2#h1
    
        url = 'http://hello.world?p0=v0#h1';
        params = {'p1': 'v1', 'p2': 'v2'};
        console.log('=> ', UrlParameters.appendParametersToUrl(url, params));
        // Output: http://hello.world?p0=v0&p1=v1&p2=v2#h1
    

提交回复
热议问题