Pass variables into javascript via query strings


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

Pass variables into javascript files using query strings, and return them using getJSvars()
Example

//HTML


//return the value of "foo"
getJSvars('filename.js', 'foo');


Copy this code and paste it in your HTML
  1. function getJSvars(script_name, var_name, if_empty) {
  2.  
  3. var script_elements = document.getElementsByTagName('script');
  4.  
  5. if(if_empty == null) {var if_empty = '';}
  6.  
  7. for (a = 0; a < script_elements.length; a++) {
  8. var source_string = script_elements[a].src;
  9. if(source_string.indexOf(script_name)>=0) {
  10.  
  11. var_name = var_name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  12. var regex_string = new RegExp("[\\?&]"+var_name+"=([^&#]*)");
  13. var parsed_vars = regex_string.exec(source_string);
  14. if(parsed_vars == null) { return if_empty; }
  15. else { return parsed_vars[1]; }
  16.  
  17. }
  18. }
  19. }

URL: http://posheika.net/?p=42

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.