yosup/js/ui/safe-html.js
Thomas Mathews a78d80d118 This repo now only contains the web app.
I did this because they are 2 separate concerns and I have diverged
so far from the original repo. I didn't start a new repo because it
contains valuable history of all the people who contributed to it.

Additionally if there is an issue with this we can revert, but I
rather not. Forks are forks.
2022-12-22 11:07:35 -08:00

38 lines
897 B
JavaScript

// https://github.com/AntonioVdlC/html-template-tag
const chars = {
"&": "&",
">": ">",
"<": "&lt;",
'"': "&quot;",
"'": "&#39;",
"`": "&#96;",
};
// Dynamically create a RegExp from the `chars` object
const re = new RegExp(Object.keys(chars).join("|"), "g");
// Return the escaped string
function escape(str) {
return String(str).replace(re, (match) => chars[match]);
}
function html(
literals,
...substs
) {
return literals.raw.reduce((acc, lit, i) => {
let subst = substs[i - 1];
if (Array.isArray(subst)) {
subst = subst.join("");
} else if (literals.raw[i - 1] && literals.raw[i - 1].endsWith("$")) {
// If the interpolation is preceded by a dollar sign,
// substitution is considered safe and will not be escaped
acc = acc.slice(0, -1);
} else {
subst = escape(subst);
}
return acc + subst + lit;
});
}