Skip to content

Instantly share code, notes, and snippets.

@reifman
Last active February 27, 2017 15:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save reifman/4651687 to your computer and use it in GitHub Desktop.
Save reifman/4651687 to your computer and use it in GitHub Desktop.
Javascript to parse query string variables from URL
<script>
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&amp;");
for (var i=0;i&lt;vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
</script>
// To test, make a request to page.html?x=Hello
<script>
alert( getQueryVariable(“x”) );
</script>
@taylorbyte
Copy link

I couldn't get the first variable after the '?'
e.g.:
URL: http://127.0.0.1/video.html?play=file.mp4&testvar=12345

pair play=file.mp4 was undetectable
pair testvar=12345 was

so I used the following to include the '?'

var vars = query.split(/[?,&]+/);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment