Skip to content

Instantly share code, notes, and snippets.

@laurendorman
Created February 14, 2019 17:45
Show Gist options
  • Save laurendorman/f88d753515e57d6d5df0d40c5372d011 to your computer and use it in GitHub Desktop.
Save laurendorman/f88d753515e57d6d5df0d40c5372d011 to your computer and use it in GitHub Desktop.
Update query params in URI
export default function updateQuery(params) {
window.location.search = encodeURIParams(mergeObjects(decodeURIParams(), params), true);
};
function decodeURIParams(query) {
if (query == null) {
query = window.location.search;
}
if (query[0] == '?') {
query = query.substring(1);
}
var params = query.split('&');
var result = {};
for (let i = 0; i < params.length; i++) {
const param = params[i];
const pos = param.indexOf('=');
if (pos >= 0) {
const key = decodeURIComponent(param.substring(0, pos));
const val = decodeURIComponent(param.substring(pos + 1));
result[key] = val;
} else {
const key = decodeURIComponent(param);
}
}
return result;
}
function encodeURIParams(params, addQuestionMark) {
const pairs = [];
for (const key in params) if (params.hasOwnProperty(key)) {
const value = params[key];
if (value != null) /* matches null and undefined */ {
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(value))
}
}
if (pairs.length == 0) {
return '';
}
return (addQuestionMark ? '?' : '') + pairs.join('&');
}
function mergeObjects(destination, source) {
for (var key in source) if (source.hasOwnProperty(key)) {
destination[key] = source[key];
}
return destination;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment