escapeHtml()
转义字符串中的 HTML 特殊字符。
import { escapeHtml } from "@unifast/core";签名
function escapeHtml(str: string): string参数
str
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
str | string | — | 包含需要转义字符的字符串 |
返回值
string —— 将 &、<、> 和 " 替换为相应 HTML 实体后的字符串。
用法
import { escapeHtml } from "@unifast/core";
const safe = escapeHtml('<script>alert("xss")</script>');
console.log(safe);
// <script>alert("xss")</script>示例
基础转义
import { escapeHtml } from "@unifast/core";
console.log(escapeHtml("Tom & Jerry"));
// Tom & Jerry
console.log(escapeHtml('class="main"'));
// class="main"
console.log(escapeHtml("1 < 2 > 0"));
// 1 < 2 > 0转义用户生成的内容
import { escapeHtml } from "@unifast/core";
const userComment = '<img src=x onerror="alert(1)">';
const html = `<div class="comment"></div>`;
console.log(html);
// <div class="comment"><img src=x onerror="alert(1)"></div>构建安全的 HTML 属性
import { escapeHtml } from "@unifast/core";
const title = 'He said "hello" & waved';
const html = `<span title="">Hover me</span>`;
console.log(html);
// <span title="He said "hello" & waved">Hover me</span>行为说明
&会被替换为&<会被替换为<>会被替换为>"会被替换为"其他字符保持不变