From ad2e7ad196cd9c89e297f52d6974b1098bf8e61a Mon Sep 17 00:00:00 2001 From: Tangent Wantwight Date: Sun, 6 Aug 2023 02:38:42 -0400 Subject: [PATCH] DOM-less escapeHTML implementation --- src/helpers.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/src/helpers.ts b/src/helpers.ts index 7e5969d..84fbc00 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -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 "&"; + case "<": + return "<"; + case ">": + return ">"; + case '"': + return """; + case "'": + return "'"; + default: + return char; + } + }); }