Created
April 10, 2019 12:22
-
-
Save jon-grangien/2f848f6bb09505266ab01cc101f58407 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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