[javascript] Change URL parameters

I have this URL:

site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc

what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10).

This question is related to javascript url query-string url-parameters url-parsing

The answer is


Ben Alman has a good jquery querystring/url plugin here that allows you to manipulate the querystring easily.

As requested -

Goto his test page here

In firebug enter the following into the console

jQuery.param.querystring(window.location.href, 'a=3&newValue=100');

It will return you the following amended url string

http://benalman.com/code/test/js-jquery-url-querystring.html?a=3&b=Y&c=Z&newValue=100#n=1&o=2&p=3

Notice the a querystring value for a has changed from X to 3 and it has added the new value.

You can then use the new url string however you wish e.g using document.location = newUrl or change an anchor link etc


Would a viable alternative to String manipulation be to set up an html form and just modify the value of the rows element?

So, with html that is something like

<form id='myForm' target='site.fwx'>
    <input type='hidden' name='position' value='1'/>
    <input type='hidden' name='archiveid' value='5000'/>
    <input type='hidden' name='columns' value='5'/>
    <input type='hidden' name='rows' value='20'/>
    <input type='hidden' name='sorting' value='ModifiedTimeAsc'/>
</form>

With the following JavaScript to submit the form

var myForm = document.getElementById('myForm');
myForm.rows.value = yourNewValue;
myForm.submit();

Probably not suitable for all situations, but might be nicer than parsing the URL string.


I just wrote a simple module to deal with reading and updating the current url query params.

Example usage:

import UrlParams from './UrlParams'

UrlParams.remove('foo') //removes all occurences of foo=?
UrlParams.set('foo', 'bar') //set all occurences of foo equal to bar
UrlParams.add('foo', 'bar2') //add bar2 to foo result: foo=bar&foo=bar2
UrlParams.get('foo') //returns bar
UrlParams.get('foo', true) //returns [bar, bar2]

Here is my code named UrlParams.(js/ts):

class UrlParams {

    /**
     * Get params from current url
     * 
     * @returns URLSearchParams
     */
    static getParams(){
        let url = new URL(window.location.href)
        return new URLSearchParams(url.search.slice(1))
    }

    /**
     * Update current url with params
     * 
     * @param params URLSearchParams
     */
    static update(params){
        if(`${params}`){
            window.history.replaceState({}, '', `${location.pathname}?${params}`)
        } else {
            window.history.replaceState({}, '', `${location.pathname}`)
        }
    }

    /**
     * Remove key from url query
     * 
     * @param param string
     */
    static remove(param){
        let params = this.getParams()
        if(params.has(param)){
            params.delete(param)
            this.update(params)
        }
    }

    /**
     * Add key value pair to current url
     * 
     * @param key string
     * @param value string
     */
    static add(key, value){
        let params = this.getParams()
        params.append(key, value)
        this.update(params)
    }

    /**
     * Get value or values of key
     * 
     * @param param string
     * @param all string | string[]
     */
    static get(param, all=false){
        let params = this.getParams()
        if(all){
            return params.getAll(param)
        }
        return params.get(param)
    }

    /**
     * Set value of query param
     * 
     * @param key string
     * @param value string
     */
    static set(key, value){
        let params = this.getParams()
        params.set(key, value)
        this.update(params)
    }

}
export default UrlParams
export { UrlParams }

you can do it via normal JS also

var url = document.URL
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var aditionalURL = tempArray[1]; 
var temp = "";
if(aditionalURL)
{
var tempArray = aditionalURL.split("&");
for ( var i in tempArray ){
    if(tempArray[i].indexOf("rows") == -1){
            newAdditionalURL += temp+tempArray[i];
                temp = "&";
            }
        }
}
var rows_txt = temp+"rows=10";
var finalURL = baseURL+"?"+newAdditionalURL+rows_txt;

I know this is an old question. I have enhanced the function above to add or update query params. Still a pure JS solution only.

                      function addOrUpdateQueryParam(param, newval, search) {

                        var questionIndex = search.indexOf('?');

                        if (questionIndex < 0) {
                            search = search + '?';
                            search = search + param + '=' + newval;
                            return search;
                        }

                        var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
                        var query = search.replace(regex, "$1").replace(/&$/, '');

                        var indexOfEquals = query.indexOf('=');

                        return (indexOfEquals >= 0 ? query + '&' : query + '') + (newval ? param + '=' + newval : '');
                    }

2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.

var setSearchParam = function(key, value) {
    if (!window.history.pushState) {
        return;
    }

    if (!key) {
        return;
    }

    var url = new URL(window.location.href);
    var params = new window.URLSearchParams(window.location.search);
    if (value === undefined || value === null) {
        params.delete(key);
    } else {
        params.set(key, value);
    }

    url.search = params;
    url = url.toString();
    window.history.replaceState({url: url}, null, url);
}

I've extended Sujoy's code to make up a function.

/**
 * http://stackoverflow.com/a/10997390/11236
 */
function updateURLParameter(url, param, paramVal){
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";
    if (additionalURL) {
        tempArray = additionalURL.split("&");
        for (var i=0; i<tempArray.length; i++){
            if(tempArray[i].split('=')[0] != param){
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }
    }

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}

Function Calls:

var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');

window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));

Updated version that also take care of the anchors on the URL.

function updateURLParameter(url, param, paramVal)
{
    var TheAnchor = null;
    var newAdditionalURL = "";
    var tempArray = url.split("?");
    var baseURL = tempArray[0];
    var additionalURL = tempArray[1];
    var temp = "";

    if (additionalURL) 
    {
        var tmpAnchor = additionalURL.split("#");
        var TheParams = tmpAnchor[0];
            TheAnchor = tmpAnchor[1];
        if(TheAnchor)
            additionalURL = TheParams;

        tempArray = additionalURL.split("&");

        for (var i=0; i<tempArray.length; i++)
        {
            if(tempArray[i].split('=')[0] != param)
            {
                newAdditionalURL += temp + tempArray[i];
                temp = "&";
            }
        }        
    }
    else
    {
        var tmpAnchor = baseURL.split("#");
        var TheParams = tmpAnchor[0];
            TheAnchor  = tmpAnchor[1];

        if(TheParams)
            baseURL = TheParams;
    }

    if(TheAnchor)
        paramVal += "#" + TheAnchor;

    var rows_txt = temp + "" + param + "=" + paramVal;
    return baseURL + "?" + newAdditionalURL + rows_txt;
}

I was looking for the same thing and found: https://github.com/medialize/URI.js which is quite nice :)

-- Update

I found a better package: https://www.npmjs.org/package/qs it also deals with arrays in get params.


I think you want the query plugin.

E.g.:

window.location.search = jQuery.query.set("rows", 10);

This will work regardless of the current state of rows.


Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:

window.history.replaceState('object or string', 'Title', 'page.html' + editParams('sorting', ModifiedTimeAsc));


// background functions below:

// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
  key = encodeURI(key);

  var params = getSearchParameters();

  if (Object.keys(params).length === 0) {
    if (value !== false)
      return '?' + key + '=' + encodeURI(value);
    else
      return '';
  }

  if (value !== false)
    params[key] = encodeURI(value);
  else
    delete params[key];

  if (Object.keys(params).length === 0)
    return '';

  return '?' + $.map(params, function (value, key) {
    return key + '=' + value;
  }).join('&');
}

// Get object/associative array of URL parameters
function getSearchParameters () {
  var prmstr = window.location.search.substr(1);
  return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}

// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
  var params = {},
      prmarr = prmstr.split("&");

  for (var i = 0; i < prmarr.length; i++) {
    var tmparr = prmarr[i].split("=");
    params[tmparr[0]] = tmparr[1];
  }
  return params;
}

My solution:

const setParams = (data) => {
    if (typeof data !== 'undefined' && typeof data !== 'object') {
        return
    }

    let url = new URL(window.location.href)
    const params = new URLSearchParams(url.search)

    for (const key of Object.keys(data)) {
        if (data[key] == 0) {
            params.delete(key)
        } else {
            params.set(key, data[key])
        }
    }

    url.search = params
    url = url.toString()
    window.history.replaceState({ url: url }, null, url)
}

Then just call "setParams" and pass an object with data you want to set.

Example:

$('select').on('change', e => {
    const $this = $(e.currentTarget)
    setParams({ $this.attr('name'): $this.val() })
})

In my case I had to update a html select input when it changes and if the value is "0", remove the parameter. You can edit the function and remove the parameter from the url if the object key is "null" as well.

Hope this helps yall


You can use this my library to do the job: https://github.com/Mikhus/jsurl

var url = new Url('site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc');
url.query.rows = 10;
alert( url);

Using javascript URL:

var url = new URL(window.location);
(url.searchParams.has('rows') ? url.searchParams.set('rows', rows) : url.searchParams.append('rows', rows));
window.location = url;

If you want to change the url in address bar:

const search = new URLSearchParams(location.search);
search.set('rows', 10);
location.search = search.toString();

Note, changing location.search reloads the page.


Another variation on Sujoy's answer. Just changed the variable names & added a namespace wrapper:

window.MyNamespace = window.MyNamespace  || {};
window.MyNamespace.Uri = window.MyNamespace.Uri || {};

(function (ns) {

    ns.SetQueryStringParameter = function(url, parameterName, parameterValue) {

        var otherQueryStringParameters = "";

        var urlParts = url.split("?");

        var baseUrl = urlParts[0];
        var queryString = urlParts[1];

        var itemSeparator = "";
        if (queryString) {

            var queryStringParts = queryString.split("&");

            for (var i = 0; i < queryStringParts.length; i++){

                if(queryStringParts[i].split('=')[0] != parameterName){

                    otherQueryStringParameters += itemSeparator + queryStringParts[i];
                    itemSeparator = "&";
                }
            }
        }

        var newQueryStringParameter = itemSeparator + parameterName + "=" + parameterValue;

        return baseUrl + "?" + otherQueryStringParameters + newQueryStringParameter;
    };

})(window.MyNamespace.Uri);

Useage is now:

var changedUrl = MyNamespace.Uri.SetQueryStringParameter(originalUrl, "CarType", "Ford");

No library, using URL() WebAPI (https://developer.mozilla.org/en-US/docs/Web/API/URL)

function setURLParameter(url, parameter, value) {
    let url = new URL(url);
    if (url.searchParams.get(parameter) === value) {
        return url;
    }
    url.searchParams.set(parameter, value);
    return url.href;
}

This doesn't work on IE: https://developer.mozilla.org/en-US/docs/Web/API/URL#Browser_compatibility


I wrote a little helper function that works with any select. All you need to do is add the class "redirectOnChange" to any select element, and this will cause the page to reload with a new/changed querystring parameter, equal to the id and value of the select, e.g:

<select id="myValue" class="redirectOnChange"> 
    <option value="222">test222</option>
    <option value="333">test333</option>
</select>

The above example would add "?myValue=222" or "?myValue=333" (or using "&" if other params exist), and reload the page.

jQuery:

$(document).ready(function () {

    //Redirect on Change
    $(".redirectOnChange").change(function () {
        var href = window.location.href.substring(0, window.location.href.indexOf('?'));
        var qs = window.location.href.substring(window.location.href.indexOf('?') + 1, window.location.href.length);
        var newParam = $(this).attr("id") + '=' + $(this).val();

        if (qs.indexOf($(this).attr("id") + '=') == -1) {
            if (qs == '') {
                qs = '?'
            }
            else {
                qs = qs + '&'
            }
            qs = qs + newParam;

        }
        else {
            var start = qs.indexOf($(this).attr("id") + "=");
            var end = qs.indexOf("&", start);
            if (end == -1) {
                end = qs.length;
            }
            var curParam = qs.substring(start, end);
            qs = qs.replace(curParam, newParam);
        }
        window.location.replace(href + '?' + qs);
    });
});

This is the modern way to change URL parameters:

function setGetParam(key,value) {
  if (history.pushState) {
    var params = new URLSearchParams(window.location.search);
    params.set(key, value);
    var newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + params.toString();
    window.history.pushState({path:newUrl},'',newUrl);
  }
}

I too have written a library for getting and setting URL query parameters in JavaScript.

Here is an example of its usage.

var url = Qurl.create()
  , query
  , foo
  ;

Get query params as an object, by key, or add/change/remove.

// returns { foo: 'bar', baz: 'qux' } for ?foo=bar&baz=qux
query = url.query();

// get the current value of foo
foo = url.query('foo');

// set ?foo=bar&baz=qux
url.query('foo', 'bar');
url.query('baz', 'qux');

// unset foo, leaving ?baz=qux
url.query('foo', false); // unsets foo

     // usage: clear ; cd src/js/node/js-unit-tests/01-set-url-param ; npm test ; cd -
     // prereqs: , nodejs , mocha
     // URI = scheme:[//authority]path[?paramName1=paramValue1&paramName2=paramValue2][#fragment]
     // call by: uri = uri.setUriParam("as","md")
     String.prototype.setUriParam = function (paramName, paramValue) {
        var uri = this
        var fragment = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
        uri = ( uri.indexOf('#') === -1 ) ? uri : uri.split('#')[0]
        if ( uri.indexOf("?") === -1 ) { uri = uri + '?&' }
        uri = uri.replace ( '?' + paramName , '?&' + paramName)
        var toRepl = (paramValue != null) ? ('$1' + paramValue) : ''
        var toSrch = new RegExp('([&]' + paramName + '=)(([^&#]*)?)')
        uri = uri.replace(toSrch,toRepl)
        if (uri.indexOf(paramName + '=') === -1 && toRepl != '' ) {
           var ampersandMayBe = uri.endsWith('&') ? '' : '&'
           uri = uri + ampersandMayBe + paramName + "=" + String(paramValue)
        }
        uri = ( fragment.length == 0 ) ? uri : (uri+"#"+fragment) //may-be re-add the fragment
        return uri
     }

     var assert = require('assert');
     describe('replacing url param value', function () {

        // scheme://authority/path[?p1=v1&p2=v2#fragment
        // a clean url
        it('http://org.com/path -> http://org.com/path?&prm=tgt_v', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
           var uriActual = uri.setUriParam("bid",10)
           assert.equal(uriActual, uriExpected);
        });

        // has the url param existing after the ? with num value
        it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=57'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
           var uriActual = uri.setUriParam("bid",10)
           assert.equal(uriActual, uriExpected);
        });

        // has the url param existing after the ? but string value
        it('http://org.com/path?prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=boo-bar'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=boo-bar-baz'
           var uriActual = uri.setUriParam("bid","boo-bar-baz")
           assert.equal(uriActual, uriExpected);
        });

        // has the url param existing after the ?& but string value
        it('http://org.com/path?&prm=src_v -> http://org.com/path?&prm=tgt_v', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10'
           var uriActual = uri.setUriParam("bid",10)
           assert.equal(uriActual, uriExpected);
        });

        // has the url param existing after the ? with other param
        it('http://org.com/path?prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v'
           var uriActual = uri.setUriParam("bid",10)
           assert.equal(uriActual, uriExpected);
        });

        // has the url param existing after the ?& with other param
        it('http://org.com/path?&prm=src_v&other_p=other_v -> http://org.com/path?&prm=tgt_v&other_p=other_v', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v'
           var uriActual = uri.setUriParam("bid",10)
           assert.equal(uriActual, uriExpected);
        });

        // has the url param existing after the ? with other param with fragment
        it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p=other_v#f'
           var uriActual = uri.setUriParam("bid",10)
           assert.equal(uriActual, uriExpected);
        });

        // has the url param existing after the ?& with other param with fragment
        it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p&other_v#f'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=10&other_p&other_v#f'
           var uriActual = uri.setUriParam("bid",10)
           assert.equal(uriActual, uriExpected);
        });

        // remove the param-name , param-value pair
        it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?bid=5&other_p=other_v#f'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
           var uriActual = uri.setUriParam("bid",null)
           assert.equal(uriActual, uriExpected);
        });

        // remove the param-name , param-value pair
        it('http://org.com/path?&prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&bid=5&other_p=other_v#f'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
           var uriActual = uri.setUriParam("bid",null)
           assert.equal(uriActual, uriExpected);
        });

        // add a new param name , param value pair
        it('http://org.com/path?prm=src_v&other_p=other_v#f -> http://org.com/path?&prm=tgt_v&other_p=other_v#f', function (){
           var uri = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v#f'
           var uriExpected = 'http://site.eu:80/qto/view/devops_guide_doc?&other_p=other_v&bid=foo-bar#f'
           var uriActual = uri.setUriParam("bid","foo-bar")
           assert.equal(uriActual, uriExpected);
        });

     });

Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.

/**
 * Adds or updates a URL parameter.
 *
 * @param {string} url  the URL to modify
 * @param {string} param  the name of the parameter
 * @param {string} paramVal  the new value for the parameter
 * @return {string}  the updated URL
 */
self.setParameter = function (url, param, paramVal){
  // http://stackoverflow.com/a/10997390/2391566
  var parts = url.split('?');
  var baseUrl = parts[0];
  var oldQueryString = parts[1];
  var newParameters = [];
  if (oldQueryString) {
    var oldParameters = oldQueryString.split('&');
    for (var i = 0; i < oldParameters.length; i++) {
      if(oldParameters[i].split('=')[0] != param) {
        newParameters.push(oldParameters[i]);
      }
    }
  }
  if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
    newParameters.push(param + '=' + encodeURI(paramVal));
  }
  if (newParameters.length > 0) {
    return baseUrl + '?' + newParameters.join('&');
  } else {
    return baseUrl;
  }
}

I think we use the URLSearchParams to get and set the parameters value into href

Here is the example to get the current URL and set the value of the parameter test

let newUrl = new URL(window.location.href);
let params = new URLSearchParams(newUrl.search);
params.set('test', testValue);
newUrl.search = params;
newUrl        = newUrl.toString();
history.pushState({}, null, newUrl);

URL query parameters can be easily modified using URLSearchParams and History interfaces:

// Construct URLSearchParams object instance from current URL querystring.
var queryParams = new URLSearchParams(window.location.search);
 
// Set new or modify existing parameter value. 
//queryParams.set("myParam", "myValue");
queryParams.set("rows", "10");
 
// Replace current querystring with the new one.
history.replaceState(null, null, "?"+queryParams.toString());

Alternatively instead of modifying current history entry using replaceState() we can use pushState() method to create a new one:

history.pushState(null, null, "?"+queryParams.toString());

https://zgadzaj.com/development/javascript/how-to-change-url-query-parameter-with-javascript-only


Here is a simple solution using the query-string library.

const qs = require('query-string')
function addQuery(key, value) {
  const q = qs.parse(location.search)
  const url = qs.stringifyUrl(
    {
      url: location.pathname,
      query: {
      ...q,
      [key]: value,
      },
    },
    { skipEmptyString: true }
  );
  window.location.href = url
  // if you are using Turbolinks
  // add this: Turbolinks.visit(url)
}
// Usage
addQuery('page', 2)

If you are using react without react-router

export function useAddQuery() {
  const location = window.location;
  const addQuery = useCallback(
    (key, value) => {
      const q = qs.parse(location.search);
      const url = qs.stringifyUrl(
        {
          url: location.pathname,
          query: {
            ...q,
            [key]: value,
          },
        },
        { skipEmptyString: true }
      );
      window.location.href = url
    },
    [location]
  );

  return { addQuery };
}
// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)

If you are using react with react-router

export function useAddQuery() {
  const location = useLocation();
  const history = useHistory();

  const addQuery = useCallback(
    (key, value) => {
      let pathname = location.pathname;
      let searchParams = new URLSearchParams(location.search);
      searchParams.set(key, value);
      history.push({
        pathname: pathname,
        search: searchParams.toString()
      });
    },
    [location, history]
  );

  return { addQuery };
}

// Usage
const { addQuery } = useAddQuery()
addQuery('page', 2)

PS: qs is the import from query-string module.


A modern approach to this is to use native standard based URLSearchParams. It's supported by all major browsers, except for IE where they're polyfills available

const paramsString = "site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc"
const searchParams = new URLSearchParams(paramsString);
searchParams.set('rows', 10);
console.log(searchParams.toString()); // return modified string.

my function support removing param

function updateURLParameter(url, param, paramVal, remove = false) {
        var newAdditionalURL = '';
        var tempArray = url.split('?');
        var baseURL = tempArray[0];
        var additionalURL = tempArray[1];
        var rows_txt = '';

        if (additionalURL)
            newAdditionalURL = decodeURI(additionalURL) + '&';

        if (remove)
            newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
        else
            rows_txt = param + '=' + paramVal;

        window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
    }

Quick little solution in pure js, no plugins needed:

function replaceQueryParam(param, newval, search) {
    var regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?");
    var query = search.replace(regex, "$1").replace(/&$/, '');

    return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : '');
}

Call it like this:

 window.location = '/mypage' + replaceQueryParam('rows', 55, window.location.search)

Or, if you want to stay on the same page and replace multiple params:

 var str = window.location.search
 str = replaceQueryParam('rows', 55, str)
 str = replaceQueryParam('cols', 'no', str)
 window.location = window.location.pathname + str

edit, thanks Luke: To remove the parameter entirely, pass false or null for the value: replaceQueryParam('rows', false, params). Since 0 is also falsy, specify '0'.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to url

What is the difference between URL parameters and query strings? Allow Access-Control-Allow-Origin header using HTML5 fetch API File URL "Not allowed to load local resource" in the Internet Browser Slack URL to open a channel from browser Getting absolute URLs using ASP.NET Core How do I load an HTTP URL with App Transport Security enabled in iOS 9? Adding form action in html in laravel React-router urls don't work when refreshing or writing manually URL for public Amazon S3 bucket How can I append a query parameter to an existing URL?

Examples related to query-string

How can I get (query string) parameters from the URL in Next.js? How to read values from the querystring with ASP.NET Core? What is the difference between URL parameters and query strings? How to get URL parameter using jQuery or plain JavaScript? How to access the GET parameters after "?" in Express? node.js http 'get' request with query string parameters Escaping ampersand in URL In Go's http package, how do I get the query string on a POST request? Append values to query string Node.js: Difference between req.query[] and req.params

Examples related to url-parameters

What is the difference between URL parameters and query strings? RestTemplate: How to send URL and query parameters together How can I get query parameters from a URL in Vue.js? How can I get the named parameters from a URL using Flask? How to get a URL parameter in Express? PHP check if url parameter exists Pass Hidden parameters using response.sendRedirect() How to convert URL parameters to a JavaScript object? How to replace url parameter with javascript/jquery? Username and password in https url

Examples related to url-parsing

How to get parameters from a URL string? How to convert URL parameters to a JavaScript object? Change URL parameters