Created
February 21, 2020 19:53
-
-
Save d4mation/392bf17a1faeb054043a2b58c34c8cd6 to your computer and use it in GitHub Desktop.
Easily update/get a URL Parameter via JS. I keep needing this and forget what projects I used it in, so here we go.
This file contains hidden or 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
/** | |
* Gets a Value from a Query String by Key | |
* | |
* @param {string} queryString Query String | |
* @param {string} key | |
* | |
* @since 1.0.0 | |
* @return {string} Query String | |
*/ | |
function getURLParam( queryString, key ) { | |
var vars = queryString.replace( /^\?/, '' ).split( '&' ); | |
for ( var i = 0; i < vars.length; i++ ) { | |
var pair = vars[ i ].split( '=' ); | |
if ( pair[0] == key ) { | |
return pair[1]; | |
} | |
} | |
return false; | |
} | |
/** | |
* Update a URL Query String Param by Key, preserving any Hash | |
* | |
* @param {string} queryString URL | |
* @param {string} key Query Stirng Param Key | |
* @param {string} value Query String Param Value | |
* | |
* @since 1.0.0 | |
* @return {string} URL | |
*/ | |
function updateURLParam( queryString, key, value ) { | |
// remove the hash part before operating on the url | |
var hashIndex = queryString.indexOf( '#' ); | |
var hash = hashIndex === -1 ? '' : queryString.substr( hashIndex ); | |
queryString = hashIndex === -1 ? queryString : queryString.substr( 0, hashIndex ); | |
var re = new RegExp( "([?&])" + key + "=.*?(&|$)", "i" ); | |
var separator = queryString.indexOf( '?' ) !== -1 ? "&" : "?"; | |
if ( queryString.match( re ) && value !== '' ) { | |
queryString = queryString.replace( re, '$1' + key + "=" + value + '$2' ); | |
} | |
else if ( value.length == 0 ) { | |
let temp = queryString.replace( re, '' ); | |
if ( temp.length == 0 ) { | |
queryString = temp; | |
} | |
else { | |
queryString = '?' + temp; | |
} | |
} | |
else { | |
queryString = queryString + separator + key + "=" + value; | |
} | |
return queryString + hash; | |
} | |
export { | |
getURLParam, | |
updateURLParam | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment