-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhtml-esc.js
More file actions
31 lines (27 loc) · 1.06 KB
/
html-esc.js
File metadata and controls
31 lines (27 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// html-esc
// JavaScript Template Literal Tag to output HTML-escaped content. Eg. `` html`<div>${myVar}</div>` ``
// Barebones alternative to `lit-html` and `htl`.
// Credit to developit/vhtml, initially used `createElement().textContent` sanitization but needed regex for attr delimiters.
const map = { "&": "amp", "<": "lt", ">": "gt", '"': "quot", "'": "apos" };
const esc = (str) => str.replace(/[&<>"']/g, (s) => `&${map[s]};`);
// Sanitized string marking inspired by dodoas/stringjsx
const markSafe = (str) =>
Object.assign(new String(str), { __html_sanitized: true });
function htmlSanitize(rawText = "") {
if (rawText?.__html_sanitized) return rawText;
return markSafe(esc(rawText));
}
export function html(strings, ...values) {
return markSafe(
strings.reduce((acc, curr, i) => {
const interpolatedValue = values[i];
return (
acc +
curr +
(Array.isArray(interpolatedValue)
? interpolatedValue.map((item) => htmlSanitize(item)).join("")
: htmlSanitize(interpolatedValue))
);
}, ""),
);
}