Skip to content

Instantly share code, notes, and snippets.

@MarkVaughn
Created March 19, 2012 05:29
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save MarkVaughn/2096943 to your computer and use it in GitHub Desktop.
Save MarkVaughn/2096943 to your computer and use it in GitHub Desktop.
Get & Set URL parameter in Javascript
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);
}
@MarkVaughn
Copy link
Author

@sindresorhus
Copy link

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