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
Here's my approach: The location.params()
function (shown below) can be used as a getter or setter. Examples:
Given the URL is http://example.com/?foo=bar&baz#some-hash
,
location.params()
will return an object with all the query parameters: {foo: 'bar', baz: true}
.location.params('foo')
will return 'bar'
.location.params({foo: undefined, hello: 'world', test: true})
will change the URL to http://example.com/?baz&hello=world&test#some-hash
.Here is the params()
function, which can optionally be assigned to the window.location
object.
location.params = function(params) {
var obj = {}, i, parts, len, key, value;
if (typeof params === 'string') {
value = location.search.match(new RegExp('[?&]' + params + '=?([^&]*)[$]?'));
return value ? value[1] : undefined;
}
var _params = location.search.substr(1).split('&');
for (i = 0, len = _params.length; i < len; i++) {
parts = _params[i].split('=');
if (! parts[0]) {continue;}
obj[parts[0]] = parts[1] || true;
}
if (typeof params !== 'object') {return obj;}
for (key in params) {
value = params[key];
if (typeof value === 'undefined') {
delete obj[key];
} else {
obj[key] = value;
}
}
parts = [];
for (key in obj) {
parts.push(key + (obj[key] === true ? '' : '=' + obj[key]));
}
location.search = parts.join('&');
};