cabana/src/utils/url.js

42 lines
1.1 KiB
JavaScript
Raw Permalink Normal View History

/* eslint-disable no-restricted-globals */
2017-06-13 18:40:05 -06:00
export function objToQuery(obj) {
2017-12-12 19:24:01 -07:00
return Object.keys(obj)
.map((k) => `${k}=${encodeURIComponent(decodeURIComponent(obj[k]))}`)
.join('&');
2017-06-13 18:40:05 -06:00
}
export function getUrlParameter(name) {
const { location } = window;
name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp(`[\\?&]${name}=([^&#]*)`);
const results = regex.exec(location.search);
2017-12-12 19:24:01 -07:00
return results === null
? null
: decodeURIComponent(results[1].replace(/\+/g, ' '));
2017-06-13 18:40:05 -06:00
}
export function modifyQueryParameters({ add, remove = [] }) {
const regex = new RegExp('[\\?&]([^&#]+)=([^&#]*)');
const results = regex.exec(location.search);
2017-12-12 19:24:01 -07:00
let params = {};
if (results != null) {
for (let i = 1; i < results.length - 1; i += 2) {
const key = results[i];
const value = results[i + 1];
2017-12-12 19:24:01 -07:00
params[key] = value;
}
for (const key in params) {
2017-12-12 19:24:01 -07:00
if (remove.indexOf(key) !== -1) {
delete params[key];
}
}
params = { ...params, ...add };
} else {
params = add;
}
return `${location.origin + location.pathname}?${objToQuery(params)}`;
}