DOM-less escapeHTML implementation
This commit is contained in:
parent
62df86acb4
commit
ad2e7ad196
1 changed files with 16 additions and 3 deletions
|
@ -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;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue