htmlEscape
HTML 字符转义和反转义,用于防止 XSS 攻击和安全显示 HTML 内容。
函数签名
typescript
// 主函数
function htmlEscape(
str: string,
options?: EscapeOptions,
returnDetails?: boolean
): string | EscapeResult
// 便捷函数
function escapeHtml(str: string): string
function unescapeHtml(str: string): string
function smartEscape(str: string): string
function needsEscape(str: string): boolean
function hasEntities(str: string): boolean
type EscapeDirection = 'escape' | 'unescape' | 'both'
interface EscapeOptions {
direction?: EscapeDirection // 处理方向,默认 'escape'
}
interface EscapeResult {
original: string
escaped: string
unescaped: string
direction: EscapeDirection
hasHtmlChars: boolean
hasHtmlEntities: boolean
}参数
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
str | string | 是 | - | 需要处理的字符串 |
options.direction | 'escape' | 'unescape' | 'both' | 否 | 'escape' | 处理方向 |
returnDetails | boolean | 否 | false | 是否返回详细结果对象 |
返回值
| 类型 | 说明 |
|---|---|
string | 当 returnDetails 为 false 时,返回处理后的字符串 |
EscapeResult | 当 returnDetails 为 true 时,返回详细结果对象 |
工作原理
转义规则
将特殊字符转换为 HTML 实体:
&→&<→<>→>"→"'→'
反转义规则
将 HTML 实体转换回特殊字符(上述规则的逆向)。
处理流程
- 检查输入字符串是否为空
- 根据
direction选项执行相应操作:'escape': 使用正则替换将特殊字符转为 HTML 实体'unescape': 使用正则替换将 HTML 实体转回特殊字符'both': 检测字符串内容,智能选择转义或反转义
- 如果
returnDetails为 true,同时返回转义和反转义结果及检测信息 - 返回处理后的字符串或详细结果对象
smartEscape 函数会自动检测字符串是否已包含 HTML 实体,如果有则反转义,否则转义。