DOM-less escapeHTML implementation

This commit is contained in:
Tangent Wantwight 2023-08-06 02:38:42 -04:00
parent 62df86acb4
commit ad2e7ad196

View file

@ -1,9 +1,22 @@
const escapeDiv = document.createElement("div");
/**
* @param text Potentially dangerous text
* @returns Text safe to embed in HTML
**/
export function escapeHtml(text: string): string {
escapeDiv.textContent = text;
return escapeDiv.innerHTML;
return text.replace(/[&<>"']/g, (char) => {
switch (char) {
case "&":
return "&amp;";
case "<":
return "&lt;";
case ">":
return "&gt;";
case '"':
return "&quot;";
case "'":
return "&#039;";
default:
return char;
}
});
}