-
-
Save PeterNMcArthur/b94ceef0ed71eadaca1bf828ba417114 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
/*! | |
query-string | |
Parse and stringify URL query strings | |
https://github.com/sindresorhus/query-string | |
by Sindre Sorhus | |
MIT License | |
*/ | |
'use strict'; | |
export const queryParse = function (str) { | |
if (typeof str !== 'string') { | |
return {}; | |
} | |
str = str.trim().replace(/^\?/, ''); | |
if (!str) { | |
return {}; | |
} | |
return str.trim().split('&').reduce(function (ret, param) { | |
var parts = param.replace(/\+/g, ' ').split('='); | |
var key = parts[0]; | |
var val = parts[1]; | |
key = decodeURIComponent(key); | |
// missing `=` should be `null`: | |
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters | |
val = val === undefined ? null : decodeURIComponent(val); | |
if (!ret.hasOwnProperty(key)) { | |
ret[key] = val; | |
} else if (Array.isArray(ret[key])) { | |
ret[key].push(val); | |
} else { | |
ret[key] = [ret[key], val]; | |
} | |
return ret; | |
}, {}); | |
}; | |
export const queryStringify = function (obj) { | |
return obj ? Object.keys(obj).map(function (key) { | |
var val = obj[key]; | |
if (Array.isArray(val)) { | |
return val.map(function (val2) { | |
return encodeURIComponent(key) + '=' + encodeURIComponent(val2); | |
}).join('&'); | |
} | |
return encodeURIComponent(key) + '=' + encodeURIComponent(val); | |
}).join('&') : ''; | |
}; | |
export const queryPush = function (key, new_value) { | |
var params = queryParse(location.search); | |
params[key] = new_value; | |
var new_params_string = queryStringify(params) | |
history.pushState({}, "", window.location.pathname + '?' + new_params_string); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment