UNPKG

yizhi-html-escape

Version:

HTML escape character util

41 lines (40 loc) 1.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.unescape = exports.escape = void 0; const table_1 = require("./table"); /** * escape string to HTML special entities * @param str string * @returns */ function escape(str) { const buffer = []; let prev = 0; for (let i = 0; i < str.length; ++i) { const cc = str.charCodeAt(i); const name = table_1.escapeTable[cc]; if (name) { buffer.push(str.substring(prev, i)); buffer.push(`&${name};`); prev = i + 1; } } buffer.push(str.substring(prev)); return buffer.join(''); } exports.escape = escape; /** * unescape HTML special entities to normal string * @param str string * @returns */ function unescape(str) { return str.replace(/&((\w+)|(#\d+));/g, (match, name) => { const code = (name[0] == '#') ? parseInt(name.substr(1)) : table_1.unescapeTable[name]; if (!code || isNaN(code)) return match; return String.fromCharCode(code); }); } exports.unescape = unescape; exports.default = { escape, unescape };