Created
March 19, 2012 05:29
-
-
Save MarkVaughn/2096943 to your computer and use it in GitHub Desktop.
Get & Set URL parameter in Javascript
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
function getURLParameter(name) { | |
return decodeURIComponent( | |
(RegExp('[?|&]'+name + '=' + '(.+?)(&|$)').exec(location.search)||[null,null])[1] | |
); | |
} | |
function setURLParameter(name,value){ | |
var search; | |
if(getURLParameter(name)){ | |
search =location.search.replace(new RegExp('([?|&]'+name + '=)' + '(.+?)(&|$)'),"$1"+encodeURIComponent(value)+"$3"); | |
}else if(location.search.length){ | |
search = location.search +'&'+name + '=' +encodeURIComponent(value); | |
}else{ | |
search = '?'+name + '=' +encodeURIComponent(value); | |
} | |
History.pushState({state:History.getStateId()+1},document.title,search); | |
} |
Using regex for this is just wrong and will fail in some scenarios.
You'd better off using a tiny reusable module like:
https://github.com/sindresorhus/query-string
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses https://github.com/balupton/history.js