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>行為
&會被取代為&<會被取代為<>會被取代為>"會被取代為"其他所有字元都會保持原樣