I have this URL:
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
what I need is to be able to
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'
.
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);
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 }
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
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;
}
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 : '');
}