javascripturlquery-stringurl-parametersurl-parsing

Change URL parameters and specify defaults using JavaScript


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).


Solution

  • To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.

    You can use query-string as follows:

    // parse the query string into an object
    var q = queryString.parse(location.search);
    // set the `row` property
    q.rows = 10;
    // convert the object to a query string
    // and overwrite the existing query string
    location.search = queryString.stringify(q);