Posted By

f on 02/27/11


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

wirenaught


Attribute-value pairs from URL.


 / Published in: JavaScript
 

Interface

  • function()
  • function (string globalvariablename)
  • function (string globalvariablename, string attributevaluepair)

Description

Construct an array of attribute-value pairs from the search part of the url or an user specified string.

The result is returned from an anonymous function so the global name space won't be corrupted. A user can also provide a string to be the name of a global variable to store the result table.

Bookmarklet

The bookmarklet is generated by Closure Compiler .

  1. /* <bookmarklet> *\
  2. javascript:(function(d,a){var b,c={};if(!a)a=location.search;a=a.replace(/^\?/,"");a=a.split("&");for(b=0;b<a.length;b++)if(a[b]){a[b]=a[b].split("=");c[a[b][0]]=a[b][1]||""}if(typeof d=="string")this[d]=c;return c})();
  3. \* </bookmarklet> */
  4. (function(identifier, search)
  5. {
  6. var cx;
  7. var $_GET = {};
  8. /* Set the default value of search. */
  9. if (!search)
  10. search = location.search;
  11. /* Remove the leading question mark. */
  12. search = search.replace(/^\?/, "");
  13. /* Split attribute-value pairs. */
  14. search = search.split("&");
  15. for (cx = 0; cx < search.length; cx++)
  16. {
  17. /* Skip empty strings. */
  18. if (!search[cx])
  19. continue;
  20. /* Split attributes and values. */
  21. search[cx] = search[cx].split("=");
  22. /**
  23. * Map these attributes and values.
  24. * Undefined, the value is made an empty string.
  25. */
  26. $_GET[search[cx][0]] = search[cx][1] || "";
  27. }
  28. /* Define a global variable and store the table. */
  29. if (typeof identifier == "string")
  30. this[identifier] = $_GET;
  31. return $_GET;
  32. })();

Report this snippet  

You need to login to post a comment.