Posted By

Pjotor on 01/08/11


Tagged

String prototype query json splitter


Versions (?)

Query string mapper (String to Object)


 / Published in: JavaScript
 

URL: http://pjotor.com

A simple prototype function to make objects out of url query strings. (bonus jQuery plugin)

  1. //prototype
  2.  
  3. String.prototype.mapStr = function(objDev, keyDev){
  4. objDev = objDev || ";", keyDev = keyDev || ":";
  5. if(this.indexOf(keyDev) === -1) return this;
  6. var d = this.split(objDev);
  7. var r = {};
  8. var key, val;
  9. for(par in d){
  10. val = d[par].split(keyDev);
  11. key = val.splice(0, 1).join().replace(/^\s\s*/, '');
  12. val = val.join(keyDev).replace(/^\s\s*/, '');
  13. if (val.length > 1) {
  14. r[key.camelCase()] = val;
  15. }
  16. }
  17. return r;
  18. }
  19.  
  20. String.prototype.camelCase = function(){
  21. return this.replace(/-([a-z])/ig, function (all, letter) {
  22. return letter.toUpperCase();
  23. });
  24. }
  25.  
  26. //jQuery plugin
  27. // a little string mapper (string to object)
  28. ;(function ($) {
  29. $.map.str = function (s, objDev, keyDev) {
  30. objDev = objDev || ";", keyDev = keyDev || ":";
  31. if (s.indexOf(keyDev) === -1) return s;
  32. var d = s.split(objDev);
  33. var r = {};
  34. var key, val;
  35. for(par in d) {
  36. val = d[par].split(keyDev);
  37. key = $.trim(val.splice(0, 1).join());
  38. val = $.trim(val.join(keyDev));
  39. if (val.length > 1) {
  40. r[$.camelCase(key)] = val;
  41. }
  42. }
  43. return r;
  44. }
  45. })(jQuery);
  46.  
  47. ;(function ($) {
  48. // CamelCase object keys (ripped from jQuery since it seems to come and go in core)
  49. if ( !$.isFunction($.camelCase) ) {
  50. $.camelCase = function (string) {
  51. return string.replace(/-([a-z])/ig, function (all, letter) {
  52. return letter.toUpperCase();
  53. });
  54. }
  55. }
  56. })(jQuery);

Report this snippet  

You need to login to post a comment.