初次提交
This commit is contained in:
36
src/index.ts
Normal file
36
src/index.ts
Normal 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 }
|
Reference in New Issue
Block a user