parseQuery.js 819 B

123456789101112131415161718192021222324252627282930313233
  1. /**
  2. * Parse a query string into an object.
  3. * @param {string} [querystring] The query string.
  4. * @returns {Record<string, string>} The parsed query object.
  5. */
  6. function parseQuery(querystring) {
  7. let query = '';
  8. if (typeof querystring === 'string') {
  9. query = querystring;
  10. }
  11. /**
  12. * Transform query strings such as `?foo1=bar1&foo2=bar2`:
  13. * - remove `?` from the start
  14. * - split with `&`
  15. * - split pairs with `=`
  16. * The resulting format will be { foo1: 'bar1', foo2: 'bar2' }
  17. */
  18. return query
  19. .replace(/^\?/, '')
  20. .split('&')
  21. .reduce(function (acc, entry) {
  22. const pair = entry.split('=');
  23. // Add all non-empty entries to the accumulated object
  24. if (pair[0]) {
  25. acc[pair[0]] = pair[1];
  26. }
  27. return acc;
  28. }, {});
  29. }
  30. module.exports = parseQuery;