encode.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. var punycode = require('punycode');
  2. var revEntities = require('./reversed.json');
  3. module.exports = encode;
  4. function encode (str, opts) {
  5. if (typeof str !== 'string') {
  6. throw new TypeError('Expected a String');
  7. }
  8. if (!opts) opts = {};
  9. var numeric = true;
  10. if (opts.named) numeric = false;
  11. if (opts.numeric !== undefined) numeric = opts.numeric;
  12. var special = opts.special || {
  13. '"': true, "'": true,
  14. '<': true, '>': true,
  15. '&': true
  16. };
  17. var codePoints = punycode.ucs2.decode(str);
  18. var chars = [];
  19. for (var i = 0; i < codePoints.length; i++) {
  20. var cc = codePoints[i];
  21. var c = punycode.ucs2.encode([ cc ]);
  22. var e = revEntities[cc];
  23. if (e && (cc >= 127 || special[c]) && !numeric) {
  24. chars.push('&' + (/;$/.test(e) ? e : e + ';'));
  25. }
  26. else if (cc < 32 || cc >= 127 || special[c]) {
  27. chars.push('&#' + cc + ';');
  28. }
  29. else {
  30. chars.push(c);
  31. }
  32. }
  33. return chars.join('');
  34. }