Skip to content

Commit 97ca0b1

Browse files
committed
maint(core utils): Improve escape/unescape for safer version which makes use use of browser features.
1 parent 2a0ec96 commit 97ca0b1

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

src/core/utils.js

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -589,7 +589,9 @@ const localized_isodate = (date) => {
589589
* Replace HTML reserved characters with html entities to add HTML for user
590590
* editing to e.g. a textarea or a contenteditable.
591591
*
592-
* See: https://developer.mozilla.org/en-US/docs/Glossary/Entity#reserved_characters
592+
* See:
593+
* https://stackoverflow.com/a/22706073/1337474
594+
* https://developer.mozilla.org/en-US/docs/Glossary/Entity#reserved_characters
593595
*
594596
* @param {string} html - The HTML string to encode.
595597
*
@@ -600,17 +602,21 @@ const localized_isodate = (date) => {
600602
* ``"`` will be replaced with ``"``.
601603
*/
602604
const escape_html = (html) => {
603-
return (html || "")
604-
.replace(/&/g, "&") // needs to be first!
605-
.replace(/</g, "&lt;")
606-
.replace(/>/g, "&gt;")
607-
.replace(/"/g, "&quot;");
605+
if (!html) {
606+
return "";
607+
}
608+
const el = document.createElement("div");
609+
el.appendChild(document.createTextNode(html));
610+
// Return escaped html and also replace quotes.
611+
return el.innerHTML.replace(/"/g, "&quot;");
608612
};
609613

610614
/**
611615
* Return unescaped, raw HTML from an escaped HTML string.
612616
*
613-
* See: https://developer.mozilla.org/en-US/docs/Glossary/Entity#reserved_characters
617+
* See:
618+
* https://stackoverflow.com/a/34064434/1337474
619+
* https://developer.mozilla.org/en-US/docs/Glossary/Entity#reserved_characters
614620
*
615621
* @param {string} escaped_html - The HTML string to decode.
616622
*
@@ -621,11 +627,12 @@ const escape_html = (html) => {
621627
* ``&quot;`` will be replaced with ``"``.
622628
*/
623629
const unescape_html = (escaped_html) => {
624-
return (escaped_html || "")
625-
.replace(/&amp;/g, "&")
626-
.replace(/&lt;/g, "<")
627-
.replace(/&gt;/g, ">")
628-
.replace(/&quot;/g, '"');
630+
if (!escaped_html) {
631+
return "";
632+
}
633+
const doc = new DOMParser().parseFromString(escaped_html, "text/html");
634+
// Return unescaped html and also unescape quote named entities.
635+
return doc.documentElement.textContent.replace(/&quot;/g, '"');
629636
};
630637

631638
/**

0 commit comments

Comments
 (0)