fast and easy way of parsing query strings in JavaScript


/ Published in: CSS
Save to your folder(s)

Now make a request to page.html?x=Hello:

console.log(getQueryVariable('x'));


Copy this code and paste it in your HTML
  1. function getQueryVariable(variable) {
  2. var query = window.location.search.substring(1);
  3. var vars = query.split('&');
  4. for (var i = 0; i < vars.length; i++) {
  5. var pair = vars[i].split('=');
  6. if (decodeURIComponent(pair[0]) == variable) {
  7. return decodeURIComponent(pair[1]);
  8. }
  9. }
  10. console.log('Query variable %s not found', variable);
  11. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.