Skip to content

Instantly share code, notes, and snippets.

@tylerpaige
Created June 16, 2016 18:31
Show Gist options
  • Save tylerpaige/9c3a6321a2afcdb976e73246082839f9 to your computer and use it in GitHub Desktop.
Save tylerpaige/9c3a6321a2afcdb976e73246082839f9 to your computer and use it in GitHub Desktop.
get or set URL parameters with replaceState
/*
GETs and POSTs URL parameters
handleParam('get', ['key', 'foo'])
> { 'key' : 'value', 'foo' : 'bar'}
handleParam('post', {'key':'value', 'foo': bar})
*/
function handleParam(method, data){
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
var urlQueryString = location.search;
var hash = location.hash;
/* GET PARAMETERS FROM URL */
if(method === 'get') {
if(typeof data == 'string') {
//Single parameter to get
var key = data;
//Look for parameter in URL
var pattern = new RegExp('('+key+')(=)([0-9\\w_\\-]+)', 'g');
/*
exec returns either null or something like
['key=value', 'key', '=', 'value'] <-- we want that last item
*/
var search = pattern.exec(urlQueryString);
return search !== null ? search[search.length-1] : undefined;
} else if(typeof data == 'object') {
//Array of parameters to get
//Object to return
var p = {};
for(var i = 0, ct = data.length; i < ct; i++) {
var key = data[i];
var pattern = new RegExp('('+key+')(=)([0-9\\w_\\-]+)', 'g');
//Look for parameter in URL
var match = pattern.exec(urlQueryString);
//If key exists, save the value, otherwise undefined
p[key] = match !== null ? match[match.length-1] : undefined;
}
return p;
}
}
/* SET PARAMETERS IN URL */
else if(method === 'post') {
// Perform text transforms on a copy (nqs --> newQueryString)
var nqs = urlQueryString !== "" ? urlQueryString : '?';
for(key in data) {
// new value
var value = data[key];
// Finds something like: ['key=value', 'key', '=', 'value']
var pattern = new RegExp('('+key+')(=)([0-9\\w_\\-]+)', 'g');
var match = pattern.exec(nqs);
var newParam;
//If parameter already exists in URL
if(match !== null) {
var exParam = match[0];
//Drop the full parameter & the existing value
match = match.slice(1, match.length-1);
//Add the new value
match.push(value);
//Construct string parameter
newParam = match.join('');
//Replace existing parameter with new parameter
nqs = nqs.replace(exParam, newParam);
}
//If parameter doesn't exist in URL
else {
//Append key and value to URL
if(nqs.length == 0) {
nqs = '?';
} else if(nqs.length > 1 && nqs.indexOf('?') == 0) {
nqs = nqs + '&';
}
nqs = nqs + key + '=' + value;
}
}
//Update URL state without refreshing
window.history.replaceState({}, "", baseUrl + nqs + hash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment