Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Last active December 2, 2021 14:53
Show Gist options
  • Save bartwttewaall/09f04da9865876dd7c785ca97fecf9d5 to your computer and use it in GitHub Desktop.
Save bartwttewaall/09f04da9865876dd7c785ca97fecf9d5 to your computer and use it in GitHub Desktop.
serialize and deserialize between an object and a search string
/**
* (de)serialize an object to a search string, like ?key=value&other=more
**/
export function getSearchValues(key: string) {
const params = new URLSearchParams(location.search);
return params.get(key);
}
export function setSearchParams(key: string, value: any, push = false) {
const params = new URLSearchParams(location.search);
if (!!value) params.set(key, value.toString());
else params.delete(key);
// convert params object to a string with ? delimiter or empty
let paramString = params.toString();
paramString = !!paramString ? '?' + paramString : '';
const pathname = window.location.pathname;
if (push === true) window.history.pushState({}, '', pathname + paramString);
else window.history.replaceState({}, '', pathname + paramString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment