Parse query string from script element's src attribute


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

See javadoc style comment in source.


Copy this code and paste it in your HTML
  1. /**
  2.  * Helper object to parse the query string variables from
  3.  * <script> element's src attribute.
  4.  *
  5.  * For example, in test.html:
  6.  *
  7.  * <script src="test.js?name=value"></script>
  8.  *
  9.  * and in test.js, you can get query as name/value pairs:
  10.  *
  11.  * var queries = new ScriptQuery('test.js').parse();
  12.  * for (var name in queries) {
  13.  * var values = queries[name]; // property is Array instance.
  14.  * ...
  15.  * }
  16.  *
  17.  * If you would like to avoid array manipulation.
  18.  * ScriptQuery also provides flatten method, which returns
  19.  * only first value for each properties.
  20.  *
  21.  * var queries = new ScriptQuery('test.js').flatten();
  22.  * for (var name in queries) {
  23.  * alert(queries[name]); // property is simply string
  24.  * }
  25.  */
  26. var ScriptQuery = function(scriptPath) {
  27. this.scriptPath = scriptPath;
  28. }
  29. ScriptQuery.prototype = {
  30. get: function() {
  31. var srcRegex = new RegExp(this.scriptPath.replace('.', '\\.') + '(\\?.*)?$');
  32. var scripts = document.getElementsByTagName("script");
  33. for (var i = 0; i < scripts.length; i++) {
  34. var script = scripts[i];
  35. if (script.src && script.src.match(srcRegex)) {
  36. var query = script.src.match(/\?([^#]*)(#.*)?/);
  37. return !query ? '' : query[1];
  38. }
  39. }
  40. return '';
  41. },
  42. parse: function() {
  43. var result = {};
  44. var query = this.get();
  45. var components = query.split('&');
  46.  
  47. for (var i = 0; i < components.length; i++) {
  48. var pair = components[i].split('=');
  49. var name = pair[0], value = pair[1];
  50.  
  51. if (!result[name]) result[name] = [];
  52. // decode
  53. if (!value) {
  54. value = 'true';
  55. } else {
  56. try {
  57. value = decodeURIComponent(value);
  58. } catch (e) {
  59. value = unescape(value);
  60. }
  61. }
  62.  
  63. // MacIE way
  64. var values = result[name];
  65. values[values.length] = value;
  66. }
  67. return result;
  68. },
  69. flatten: function() {
  70. var queries = this.parse();
  71. for (var name in queries) {
  72. queries[name] = queries[name][0];
  73. }
  74. return queries;
  75. },
  76. toString: function() {
  77. return 'ScriptQuery [path=' + this.scriptPath + ']';
  78. }
  79. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.