Skip to content

Instantly share code, notes, and snippets.

@jon-grangien
Created April 10, 2019 12:22
Show Gist options
  • Save jon-grangien/2f848f6bb09505266ab01cc101f58407 to your computer and use it in GitHub Desktop.
Save jon-grangien/2f848f6bb09505266ab01cc101f58407 to your computer and use it in GitHub Desktop.
export const getUrlParameterValue = (name) => {
const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results !== null ? results[1] || 0 : null;
};
export const updateParameterInUrl = (name, value) => {
const { protocol, host, pathname, search } = window.location;
const paramReg = new RegExp(name + '=[a-z]+');
const newSearch = search.replace(paramReg, name + '=' + value);
const newUrl = protocol + "//" + host + pathname + newSearch;
window.history.pushState({ path: newUrl }, '', newUrl);
}
export const pushParameterToUrl = (fullParam) => {
const { protocol, host, pathname, search } = window.location;
const newUrl = protocol + "//" + host + pathname + search + fullParam;
window.history.pushState({ path: newUrl }, '', newUrl);
}
export const addOrUpdateParameterInUrl = (name, value) => {
if (getUrlParameterValue(name)) {
updateParameterInUrl(name, value);
} else {
const urlHasFirstParam = window.location.href.indexOf('?') > -1;
const newParam = (urlHasFirstParam ? '&' : '?') + name + '=' + value;
pushParameterToUrl(newParam);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment