Skip to content

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
}

参数

参数名类型必填默认值说明
strstring-需要处理的字符串
options.direction'escape' | 'unescape' | 'both''escape'处理方向
returnDetailsbooleanfalse是否返回详细结果对象

返回值

类型说明
stringreturnDetailsfalse 时,返回处理后的字符串
EscapeResultreturnDetailstrue 时,返回详细结果对象

工作原理

转义规则

将特殊字符转换为 HTML 实体:

  • &&
  • <&lt;
  • >&gt;
  • "&quot;
  • '&#39;

反转义规则

将 HTML 实体转换回特殊字符(上述规则的逆向)。

处理流程

  1. 检查输入字符串是否为空
  2. 根据 direction 选项执行相应操作:
    • 'escape': 使用正则替换将特殊字符转为 HTML 实体
    • 'unescape': 使用正则替换将 HTML 实体转回特殊字符
    • 'both': 检测字符串内容,智能选择转义或反转义
  3. 如果 returnDetails 为 true,同时返回转义和反转义结果及检测信息
  4. 返回处理后的字符串或详细结果对象

smartEscape 函数会自动检测字符串是否已包含 HTML 实体,如果有则反转义,否则转义。