初次提交

This commit is contained in:
2021-11-15 16:25:49 +08:00
parent 43ef43b849
commit f5eb42da7e
8 changed files with 272 additions and 1 deletions

36
src/index.ts Normal file
View File

@ -0,0 +1,36 @@
import { escapeTable, unescapeTable } from "./table"
/**
* escape string to HTML special entities
* @param str string
* @returns
*/
export function escape(str: string) {
const buffer: Array<string> = []
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
}
}
return buffer.join('')
}
/**
* unescape HTML special entities to normal string
* @param str string
* @returns
*/
export function unescape(str: string) {
return str.replace(/&(\w+);/g, (match, name, index) => {
const code = unescapeTable[name]
if (!code) return match
return String.fromCharCode(code)
})
}
export default { escape, unescape }