Posted By

nerdfiles on 11/28/09


Tagged

javascript String prototype parameter


Versions (?)

String.getParam()


 / Published in: JavaScript
 

  1. function gup( name )
  2. {
  3. name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  4. var regexS = "[\\?&]"+name+"=([^&#]*)";
  5. var regex = new RegExp( regexS );
  6. var results = regex.exec( window.location.href );
  7. if( results == null )
  8. return "";
  9. else
  10. return results[1];
  11. }
  12.  
  13. String.prototype.getParam = function(param) {
  14.  
  15. //check if url follows [http://domain.tld?parameter=value] schema
  16. var url = new RegExp(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?[\\?&]\w=(.*)?/);
  17. if (url.test(this)) {
  18.  
  19. //check if explicit parameter is sought after
  20. if (!param) {
  21. var qs = this.split("?")[1];
  22. this.param = qs.split("=")[0];
  23. param = this.param;
  24. }
  25.  
  26. //if it is, clean it
  27. param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  28.  
  29. //pull value from parameter
  30. var regexS = "[\\?&]"+param+"=([^&#]*)";
  31. var regex = new RegExp( regexS );
  32. var results = regex.exec( this );
  33. return results[1];
  34.  
  35. } else {
  36.  
  37. return false;
  38.  
  39. }
  40.  
  41. }
  42.  
  43. alert( "http://google.com?moo=cow".getParam() );

Report this snippet  

You need to login to post a comment.