How can I add or update a query string parameter?

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

    I realize this question is old and has been answered to death, but here's my stab at it. I'm trying to reinvent the wheel here because I was using the currently accepted answer and the mishandling of URL fragments recently bit me in a project.

    The function is below. It's quite long, but it was made to be as resilient as possible. I would love suggestions for shortening/improving it. I put together a small jsFiddle test suite for it (or other similar functions). If a function can pass every one of the tests there, I say it's probably good to go.

    Update: I came across a cool function for using the DOM to parse URLs, so I incorporated that technique here. It makes the function shorter and more reliable. Props to the author of that function.

    /**
     * Add or update a query string parameter. If no URI is given, we use the current
     * window.location.href value for the URI.
     * 
     * Based on the DOM URL parser described here:
     * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
     *
     * @param   (string)    uri     Optional: The URI to add or update a parameter in
     * @param   (string)    key     The key to add or update
     * @param   (string)    value   The new value to set for key
     *
     * Tested on Chrome 34, Firefox 29, IE 7 and 11
     */
    function update_query_string( uri, key, value ) {
    
        // Use window URL if no query string is provided
        if ( ! uri ) { uri = window.location.href; }
    
        // Create a dummy element to parse the URI with
        var a = document.createElement( 'a' ), 
    
            // match the key, optional square brackets, an equals sign or end of string, the optional value
            reg_ex = new RegExp( key + '((?:\\[[^\\]]*\\])?)(=|$)(.*)' ),
    
            // Setup some additional variables
            qs,
            qs_len,
            key_found = false;
    
        // Use the JS API to parse the URI 
        a.href = uri;
    
        // If the URI doesn't have a query string, add it and return
        if ( ! a.search ) {
    
            a.search = '?' + key + '=' + value;
    
            return a.href;
        }
    
        // Split the query string by ampersands
        qs = a.search.replace( /^\?/, '' ).split( /&(?:amp;)?/ );
        qs_len = qs.length; 
    
        // Loop through each query string part
        while ( qs_len > 0 ) {
    
            qs_len--;
    
            // Remove empty elements to prevent double ampersands
            if ( ! qs[qs_len] ) { qs.splice(qs_len, 1); continue; }
    
            // Check if the current part matches our key
            if ( reg_ex.test( qs[qs_len] ) ) {
    
                // Replace the current value
                qs[qs_len] = qs[qs_len].replace( reg_ex, key + '$1' ) + '=' + value;
    
                key_found = true;
            }
        }   
    
        // If we haven't replaced any occurrences above, add the new parameter and value
        if ( ! key_found ) { qs.push( key + '=' + value ); }
    
        // Set the new query string
        a.search = '?' + qs.join( '&' );
    
        return a.href;
    }
    

提交回复
热议问题