Skip to content

Instantly share code, notes, and snippets.

@BraadMartin
Created October 23, 2016 20:38
Show Gist options
  • Save BraadMartin/921e6cf51c169153bbc50354ccc29dfc to your computer and use it in GitHub Desktop.
Save BraadMartin/921e6cf51c169153bbc50354ccc29dfc to your computer and use it in GitHub Desktop.
JS query param helper functions
/**
* Insert or change a query param.
*
* See: http://stackoverflow.com/questions/486896/adding-a-parameter-to-the-url-with-javascript
*
* @param {string} key - The query param key.
* @param {string} value - The query param value.
*/
var setQueryParam = function( key, value ) {
key = encodeURI( key );
value = encodeURI( value );
var kvp = document.location.search.substr( 1 ).split( '&' );
var i = kvp.length;
var x;
while ( i-- ) {
x = kvp[ i ].split( '=' );
if ( x[0] == key ) {
x[1] = value;
kvp[ i ] = x.join( '=' );
break;
}
}
if ( i < 0 ) {
kvp[ kvp.length ] = [ key, value ].join( '=' );
}
if ( history.pushState ) {
var newURL = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + kvp.join( '&' );
window.history.pushState({
path: newURL,
}, '', newURL );
}
};
/**
* Return the value of a query param.
*
* See: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
*
* @param {string} name - The query param key to return.
*
* @return {string} - The query param value.
*/
var getQueryParam = function( name ) {
name = name.replace( /[\[\]]/g, "\\$&" );
var url = window.location.href;
var regex = new RegExp( "[?&]" + name + "(=([^&#]*)|&|#|$)" );
var results = regex.exec(url);
if ( ! results ) {
return null;
}
if ( ! results[2] ) {
return '';
}
return decodeURIComponent( results[2].replace( /\+/g, " " ) );
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment