import { escapeTable, unescapeTable } from "./table" /** * escape string to HTML special entities * @param str string * @returns */ export function escape(str: string) { const buffer: Array = [] let prev = 0 for (let i = 0; i < str.length; ++i) { const cc = str.charCodeAt(i) const name = escapeTable[cc] if (name) { buffer.push(str.substring(prev, i)) buffer.push(`&${name};`) prev = i + 1 } } buffer.push(str.substring(prev)) return buffer.join('') } /** * unescape HTML special entities to normal string * @param str string * @returns */ export function unescape(str: string) { return str.replace(/&((\w+)|(#\d+));/g, (match, name) => { const code = (name[0] == '#') ? parseInt(name.substr(1)) : unescapeTable[name] if (!code || isNaN(code)) return match return String.fromCharCode(code) }) } export default { escape, unescape }