escapeHtml()
Escape các ký tự đặc biệt của HTML trong một chuỗi.
import { escapeHtml } from "@unifast/core";Chữ ký
function escapeHtml(str: string): stringTham số
str
| Thuộc tính | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
str | string | — | Chuỗi chứa các ký tự cần escape |
Giá trị trả về
string — Chuỗi đầu vào với các ký tự &, <, > và " được thay bằng các HTML entity tương ứng.
Cách dùng
import { escapeHtml } from "@unifast/core";
const safe = escapeHtml('<script>alert("xss")</script>');
console.log(safe);
// <script>alert("xss")</script>Ví dụ
Escape cơ bản
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 > 0Escape nội dung do người dùng tạo
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>Xây dựng thuộc tính HTML an toàn
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>Hành vi
&được thay bằng&<được thay bằng<>được thay bằng>"được thay bằng"Tất cả các ký tự khác giữ nguyên