index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. var has = Object.prototype.hasOwnProperty;
  3. /**
  4. * Decode a URI encoded string.
  5. *
  6. * @param {String} input The URI encoded string.
  7. * @returns {String} The decoded string.
  8. * @api private
  9. */
  10. function decode(input) {
  11. return decodeURIComponent(input.replace(/\+/g, ' '));
  12. }
  13. /**
  14. * Simple query string parser.
  15. *
  16. * @param {String} query The query string that needs to be parsed.
  17. * @returns {Object}
  18. * @api public
  19. */
  20. function querystring(query) {
  21. var parser = /([^=?&]+)=?([^&]*)/g
  22. , result = {}
  23. , part;
  24. while (part = parser.exec(query)) {
  25. var key = decode(part[1])
  26. , value = decode(part[2]);
  27. //
  28. // Prevent overriding of existing properties. This ensures that build-in
  29. // methods like `toString` or __proto__ are not overriden by malicious
  30. // querystrings.
  31. //
  32. if (key in result) continue;
  33. result[key] = value;
  34. }
  35. return result;
  36. }
  37. /**
  38. * Transform a query string to an object.
  39. *
  40. * @param {Object} obj Object that should be transformed.
  41. * @param {String} prefix Optional prefix.
  42. * @returns {String}
  43. * @api public
  44. */
  45. function querystringify(obj, prefix) {
  46. prefix = prefix || '';
  47. var pairs = [];
  48. //
  49. // Optionally prefix with a '?' if needed
  50. //
  51. if ('string' !== typeof prefix) prefix = '?';
  52. for (var key in obj) {
  53. if (has.call(obj, key)) {
  54. pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
  55. }
  56. }
  57. return pairs.length ? prefix + pairs.join('&') : '';
  58. }
  59. //
  60. // Expose the module.
  61. //
  62. exports.stringify = querystringify;
  63. exports.parse = querystring;