decode.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. var typecast = require('../string/typecast');
  2. var isString = require('../lang/isString');
  3. var isArray = require('../lang/isArray');
  4. var hasOwn = require('../object/hasOwn');
  5. /**
  6. * Decode query string into an object of keys => vals.
  7. */
  8. function decode(queryStr, shouldTypecast) {
  9. var queryArr = (queryStr || '').replace('?', '').split('&'),
  10. count = -1,
  11. length = queryArr.length,
  12. obj = {},
  13. item, pValue, pName, toSet;
  14. while (++count < length) {
  15. item = queryArr[count].split('=');
  16. pName = item[0];
  17. if (!pName || !pName.length){
  18. continue;
  19. }
  20. pValue = shouldTypecast === false ? item[1] : typecast(item[1]);
  21. toSet = isString(pValue) ? decodeURIComponent(pValue) : pValue;
  22. if (hasOwn(obj,pName)){
  23. if(isArray(obj[pName])){
  24. obj[pName].push(toSet);
  25. } else {
  26. obj[pName] = [obj[pName],toSet];
  27. }
  28. } else {
  29. obj[pName] = toSet;
  30. }
  31. }
  32. return obj;
  33. }
  34. module.exports = decode;