index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. var has = Object.prototype.hasOwnProperty;
  3. /**
  4. * Simple query string parser.
  5. *
  6. * @param {String} query The query string that needs to be parsed.
  7. * @returns {Object}
  8. * @api public
  9. */
  10. function querystring(query) {
  11. var parser = /([^=?&]+)=?([^&]*)/g
  12. , result = {}
  13. , part;
  14. //
  15. // Little nifty parsing hack, leverage the fact that RegExp.exec increments
  16. // the lastIndex property so we can continue executing this loop until we've
  17. // parsed all results.
  18. //
  19. for (;
  20. part = parser.exec(query);
  21. result[decodeURIComponent(part[1])] = decodeURIComponent(part[2])
  22. );
  23. return result;
  24. }
  25. /**
  26. * Transform a query string to an object.
  27. *
  28. * @param {Object} obj Object that should be transformed.
  29. * @param {String} prefix Optional prefix.
  30. * @returns {String}
  31. * @api public
  32. */
  33. function querystringify(obj, prefix) {
  34. prefix = prefix || '';
  35. var pairs = [];
  36. //
  37. // Optionally prefix with a '?' if needed
  38. //
  39. if ('string' !== typeof prefix) prefix = '?';
  40. for (var key in obj) {
  41. if (has.call(obj, key)) {
  42. pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
  43. }
  44. }
  45. return pairs.length ? prefix + pairs.join('&') : '';
  46. }
  47. //
  48. // Expose the module.
  49. //
  50. exports.stringify = querystringify;
  51. exports.parse = querystring;