Attic is a cozy space with lofty ambitions.
attic.social
1const escapeEntities = new Map([
2 ["&", "&"],
3 ["<", "<"],
4 [">", ">"],
5 ['"', """],
6 ["'", "'"],
7]);
8
9const unescapeEntities = new Map([
10 ["&", "&"],
11 ["<", "<"],
12 [">", ">"],
13 [""", '"'],
14 ["'", "'"],
15]);
16
17const escapeKeys = new RegExp([...escapeEntities.keys()].join("|"), "g");
18const unescapeKeys = new RegExp([...unescapeEntities.keys()].join("|"), "g");
19
20/** Escape HTML entities */
21export const escape = (str: string): string =>
22 str.replaceAll(escapeKeys, (k) => escapeEntities.get(k)!);
23
24/** Unescape HTML entities */
25export const unescape = (str: string): string =>
26 str.replaceAll(unescapeKeys, (k) => unescapeEntities.get(k)!);
27
28/** Unescape and escape HTML entities */
29export const reEscape = (str: string) => escape(unescape(str));