Last active
August 29, 2015 13:59
-
-
Save labithiotis/10470514 to your computer and use it in GitHub Desktop.
Change Url Params JS
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
/** ==================== GET URL PARAMS AS OBJECT ==================== **/ | |
urlGetParams = function(sParams){ | |
var sHash = sParams|| window.location.hash, | |
result = {}; | |
sHash.substring(sHash.indexOf('?') + 1).split('&').forEach(function(el) { | |
var kv = el.split('='); | |
result[kv[0]] = decodeURIComponent(kv[1]); | |
}); | |
return result; | |
}; | |
/** ==================== TEST IF URL HAS PARAMS ==================== **/ | |
urlHasQuery = function( url ){ | |
var sURL = url || window.location.href; | |
return sURL.indexOf('?') != -1; | |
}; | |
/** ==================== HASH WITHOUT PARAMS ==================== **/ | |
urlHashWithoutParams = function( url ){ | |
var sURL = url ? url.substring(url.indexOf('#') + 1) : window.location.hash; | |
return sURL.split('?')[0]; | |
}; | |
/** ==================== CHANGE URL PARAMS ==================== **/ | |
urlChangeParams = function(oParams /* Object of params (Key/Value pair) to change */, aRemoveParams /* Array of params to remove */ ) { | |
var newURL = window.location.hash; | |
if ( oParams instanceof Object ) { | |
//Replace Regex | |
for(var key in oParams) { | |
if(oParams.hasOwnProperty(key)){ | |
var matchRegEx = new RegExp( "(&|\\?)" + key + "(=[^&]*)?|^" + key + "(=[^&]*)?&?" , "g"), | |
match = newURL.match(matchRegEx); | |
if(match && match.length > 0 && match[0] != ""){ | |
newURL = newURL.replace(matchRegEx, "&" + key + "=" + oParams[key]); | |
}else{ | |
newURL += ('&' + key + '=' + oParams[key]); | |
} | |
} | |
} | |
} | |
if( aRemoveParams instanceof Array ){ | |
//Remove Regex | |
for(var r = 0, rLen = aRemoveParams.length; r < rLen; r++) { | |
var removePattern = "(&|\\?)" + aRemoveParams[r] + "(=[^&]*)?|^" + aRemoveParams[r] + "(=[^&]*)?&?", | |
removeRegEx = new RegExp(removePattern, "g"); | |
newURL = newURL.replace(removeRegEx,''); | |
} | |
} | |
window.location.hash = newURL.replace(/(\?|&)$/,''); //replace any empty params with nothing | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment