Skip to content

Instantly share code, notes, and snippets.

@alexkrolick
Last active November 18, 2020 08:10
Show Gist options
  • Save alexkrolick/e305e895ce8089313134346f166545ed to your computer and use it in GitHub Desktop.
Save alexkrolick/e305e895ce8089313134346f166545ed to your computer and use it in GitHub Desktop.
Replaces the search parameter in browser URL (?param=value)
/**
* Replace browser's URL search parameter. Expects jQuery, $, or window to have .param
* defined or it will only URIencode strings and error on other types.
*/
function replaceUrlSearchParams(newParams) {
var url;
if (typeof window.URL === "function") {
url = new URL(window.location.href);
} else {
// Workaround for browsers without URL constructor:
url = document.createElement('a');
url.href = window.location.href;
}
// Encode params object with jQuery helper or equivalent serializer like
// https://github.com/knowledgecode/jquery-param/blob/master/jquery-param.js:
var searchString = serialize(newParams)
url.search = searchString;
// Change the url
replaceUrl(url.href)
// Helper functions:
function replaceUrl(url) {
var state, title;
window.history.replaceState(state, title, url)
}
function hasFunc(name, context) {
return typeof window[context][name] === "function"
}
function simpleSerializer (params) {
// URIEncode a string or error on anything else
var isAString = typeof params === 'string';
if (isAString) return encodeURIcomponent(params) // Might need to encode instead or do both
throw(
new Error('NotImplemented', 'No parameter serializer found and the parameter is not a string')
)
}
function serialize (params) {
// Try to find a serializer
var serializer;
serializer = serializer || (hasFunc('param', 'window') && window.param);
serializer = serializer || (hasFunc('jQuery', 'window') && hasFunc('param', 'jQuery') && window.jQuery.param);
serializer = serializer || (hasFunc('$', 'window') && hasFunc('param', '$') && window.$.param);
serializer = serializer || simpleSerializer;
return serializer(params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment