Skip to content

Instantly share code, notes, and snippets.

@leifoolsen
Last active September 3, 2015 11:22
Show Gist options
  • Save leifoolsen/9f89612e28307c549c1a to your computer and use it in GitHub Desktop.
Save leifoolsen/9f89612e28307c549c1a to your computer and use it in GitHub Desktop.
Get query parameter by name from given URL
function queryParameterByName(name, querystring) {
// See: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(querystring);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
(function(){
var urlString = "http://www.foo.com/my?name=foo&age=123";
console.log("name: " + queryParameterByName("name", urlString));
console.log("age : " + queryParameterByName("age", urlString));
console.log("nada: " + queryParameterByName("nada", urlString));
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment