Javascript function to get a url parameter


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



Copy this code and paste it in your HTML
  1. /**
  2. * Returns url param value
  3. * @author Arash Yalpani
  4. *
  5. * @param url The url to be queried
  6. * @param paramName The params name
  7. * @return paramName's value or false if param does not exist or is empty
  8. *
  9. * @example getUrlParam('http://localhost/?a=123', 'a') => 123
  10. * @example getUrlParam('http://localhost/?a=123', 'b') => false
  11. * @example getUrlParam('http://localhost/?a=', 'a') => false
  12. */
  13.  
  14. getUrlParam: function(url, paramName) {
  15. var urlSplit = url.split('?');
  16. if (!urlSplit[1]) { // no query
  17. return false;
  18. }
  19.  
  20. var urlQuery = urlSplit[1];
  21. var paramsSplit = urlSplit[1].split('&');
  22. for (var i = 0; i < paramsSplit.length; i++) {
  23. paramSplit = paramsSplit[i].split('=');
  24. if (paramSplit[0] == paramName) {
  25. return paramSplit[1] ? paramSplit[1] : false;
  26. }
  27. }
  28.  
  29. return false;
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.