Search code examples
javascriptjqueryregexurlparameters

How to add or replace a query parameter in a URL using Javascript/jQuery?


I'm using jQuery 1.12. I want to replace a query string parameter in my window's URL query string, or add the parameter if doesn't exist. I tried the below:

new_url = window.location.href.replace( /[\?#].*|$/, "?order_by=" + data_val )  
window.location.href = new_url 

but what I'm discovering is that this wipes out all previous parameters in the query string, which I don't want. If the query string is:

?a=1&b=2

I would want the new query string to be:

?a=2&b=2&order_by=data

and if the query string was:

?a=2&b=3&order_by=old_data

it would become:

?a=2&b=3&order_by=data

Solution

  • You could use a jQuery plugin to do the all the heavy lifting for you. It will parse the query string, and also reconstruct the updated query string for you. Much less code to deal with.

    Plugin Download Page
    Github Repo

    // URL: ?a=2&b=3&order_by=old_data
    
    var order_by = $.query.get('order_by');
    //=> old_data
    
    // Conditionally modify parameter value
    if (order_by) { 
      order_by = 'data';
    }
    
    // Inject modified parameter back into query string
    var newUrl = $.query.set('order_by', order_by).toString();
    //=> ?a=2&b=3&order_by=data
    

    For those using Node.js, there is a package for this available in NPM.

    NPM Package
    Github Repo

    var queryString = require('query-string');
    var parsed = queryString.parse('?a=2&b=3&order_by=old_data');  // location.search
    
    // Conditionally modify parameter value
    if (parsed.order_by) {
      parsed.order_by = 'data';
    }
    
    // Inject modified parameter back into query string
    const newQueryString = queryString.stringify(parsed);
    //=> a=2&b=3&order_by=data