123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- import htmlTrie from "./generated/encode-html.js";
- import { xmlReplacer, getCodePoint } from "./escape.js";
- const htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g;
- export function encodeHTML(data) {
- return encodeHTMLTrieRe(htmlReplacer, data);
- }
- export function encodeNonAsciiHTML(data) {
- return encodeHTMLTrieRe(xmlReplacer, data);
- }
- function encodeHTMLTrieRe(regExp, str) {
- let ret = "";
- let lastIdx = 0;
- let match;
- while ((match = regExp.exec(str)) !== null) {
- const i = match.index;
- ret += str.substring(lastIdx, i);
- const char = str.charCodeAt(i);
- let next = htmlTrie.get(char);
- if (typeof next === "object") {
-
- if (i + 1 < str.length) {
- const nextChar = str.charCodeAt(i + 1);
- const value = typeof next.n === "number"
- ? next.n === nextChar
- ? next.o
- : undefined
- : next.n.get(nextChar);
- if (value !== undefined) {
- ret += value;
- lastIdx = regExp.lastIndex += 1;
- continue;
- }
- }
- next = next.v;
- }
-
- if (next !== undefined) {
- ret += next;
- lastIdx = i + 1;
- }
- else {
- const cp = getCodePoint(str, i);
- ret += `&#x${cp.toString(16)};`;
-
- lastIdx = regExp.lastIndex += Number(cp !== char);
- }
- }
- return ret + str.substr(lastIdx);
- }
|