decodeUriComponent.js 749 B

12345678910111213141516171819202122232425262728293031
  1. var each = require('./each');
  2. var ucs2 = require('./ucs2');
  3. var map = require('./map');
  4. var utf8 = require('./utf8');
  5. exports = function(str) {
  6. try {
  7. return decodeURIComponent(str);
  8. } catch (e) {
  9. var matches = str.match(regMatcher);
  10. if (!matches) {
  11. return str;
  12. }
  13. each(matches, function(match) {
  14. str = str.replace(match, decode(match));
  15. });
  16. return str;
  17. }
  18. };
  19. function decode(str) {
  20. str = str.split('%').slice(1);
  21. var bytes = map(str, hexToInt);
  22. str = ucs2.encode(bytes);
  23. str = utf8.decode(str, true);
  24. return str;
  25. }
  26. function hexToInt(numStr) {
  27. return +('0x' + numStr);
  28. }
  29. var regMatcher = /(%[a-f0-9]{2})+/gi;
  30. module.exports = exports;