escapeHtml function
Escapes the characters that have a meaning in HTML (& < > " '), to insert a text in markup.
ts
import { escapeHtml } from 'utils';Signature
ts
export function escapeHtml(input: string): stringParameters
| Name | Description |
|---|---|
input | The text to escape. |
Returns
The escaped text.
Example
ts
escapeHtml('<b>"Tom & Jerry"</b>'); // '<b>"Tom & Jerry"</b>'Tests
Line coverage: 100 %.
- ✅ escapes "<b>"Tom & Jerry"</b>"
- ✅ escapes "it's"
- ✅ escapes "plain text"
- ✅ escapes "&"
- ✅ escapes ""
Source
src/string/escape-html.ts (on GitHub)
Source code
ts
/**
* Escapes the characters that have a meaning in HTML (`& < > " '`), to insert a text in markup.
*
* @param input - The text to escape.
* @returns The escaped text.
* @example
* escapeHtml('<b>"Tom & Jerry"</b>'); // '<b>"Tom & Jerry"</b>'
*/
export function escapeHtml(input: string): string {
return input
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}Test file
ts
import { escapeHtml } from './escape-html';
describe(escapeHtml, () => {
it.for([
['<b>"Tom & Jerry"</b>', '<b>"Tom & Jerry"</b>'],
["it's", 'it's'],
['plain text', 'plain text'],
['&', '&amp;'],
['', ''],
] as const)('escapes %j', ([input, expected]) => {
expect(escapeHtml(input)).toBe(expected);
});
});Keywords: escape, html, strings, function