entity.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Process html entity - {, ¯, ", ...
  2. 'use strict';
  3. var entities = require('../common/entities');
  4. var has = require('../common/utils').has;
  5. var isValidEntityCode = require('../common/utils').isValidEntityCode;
  6. var fromCodePoint = require('../common/utils').fromCodePoint;
  7. var DIGITAL_RE = /^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));/i;
  8. var NAMED_RE = /^&([a-z][a-z0-9]{1,31});/i;
  9. module.exports = function entity(state, silent) {
  10. var ch, code, match, pos = state.pos, max = state.posMax;
  11. if (state.src.charCodeAt(pos) !== 0x26/* & */) { return false; }
  12. if (pos + 1 < max) {
  13. ch = state.src.charCodeAt(pos + 1);
  14. if (ch === 0x23 /* # */) {
  15. match = state.src.slice(pos).match(DIGITAL_RE);
  16. if (match) {
  17. if (!silent) {
  18. code = match[1][0].toLowerCase() === 'x' ? parseInt(match[1].slice(1), 16) : parseInt(match[1], 10);
  19. state.pending += isValidEntityCode(code) ? fromCodePoint(code) : fromCodePoint(0xFFFD);
  20. }
  21. state.pos += match[0].length;
  22. return true;
  23. }
  24. } else {
  25. match = state.src.slice(pos).match(NAMED_RE);
  26. if (match) {
  27. if (has(entities, match[1])) {
  28. if (!silent) { state.pending += entities[match[1]]; }
  29. state.pos += match[0].length;
  30. return true;
  31. }
  32. }
  33. }
  34. }
  35. if (!silent) { state.pending += '&'; }
  36. state.pos++;
  37. return true;
  38. };