escapeHtml()
Escape HTML special characters in a string.
import { escapeHtml } from "@unifast/core";Signature
function escapeHtml(str: string): stringParameters
str
| Property | Type | Default | Description |
|---|---|---|---|
str | string | — | The string containing characters to escape |
Returns
string — The input string with &, <, >, and " replaced by their HTML entity equivalents.
Usage
import { escapeHtml } from "@unifast/core";
const safe = escapeHtml('<script>alert("xss")</script>');
console.log(safe);
// <script>alert("xss")</script>Examples
Basic escaping
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 > 0Escaping user-generated content
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>Building safe HTML attributes
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>Behavior
&is replaced with&<is replaced with<>is replaced with>"is replaced with"All other characters are left unchanged