decode.js 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. var punycode = require('punycode');
  2. var entities = require('./entities.json');
  3. module.exports = decode;
  4. function decode (str) {
  5. if (typeof str !== 'string') {
  6. throw new TypeError('Expected a String');
  7. }
  8. return str.replace(/&(#?[^;\W]+;?)/g, function (_, match) {
  9. var m;
  10. if (m = /^#(\d+);?$/.exec(match)) {
  11. return punycode.ucs2.encode([ parseInt(m[1], 10) ]);
  12. } else if (m = /^#[Xx]([A-Fa-f0-9]+);?/.exec(match)) {
  13. return punycode.ucs2.encode([ parseInt(m[1], 16) ]);
  14. } else {
  15. // named entity
  16. var hasSemi = /;$/.test(match);
  17. var withoutSemi = hasSemi ? match.replace(/;$/, '') : match;
  18. var target = entities[withoutSemi] || (hasSemi && entities[match]);
  19. if (typeof target === 'number') {
  20. return punycode.ucs2.encode([ target ]);
  21. } else if (typeof target === 'string') {
  22. return target;
  23. } else {
  24. return '&' + match;
  25. }
  26. }
  27. });
  28. }