@@ -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 */
602604const escape_html = ( html ) => {
603- return ( html || "" )
604- . replace ( / & / g, "&" ) // needs to be first!
605- . replace ( / < / g, "<" )
606- . replace ( / > / g, ">" )
607- . replace ( / " / g, """ ) ;
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, """ ) ;
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 * ``"`` will be replaced with ``"``.
622628 */
623629const unescape_html = ( escaped_html ) => {
624- return ( escaped_html || "" )
625- . replace ( / & a m p ; / g, "&" )
626- . replace ( / & l t ; / g, "<" )
627- . replace ( / & g t ; / g, ">" )
628- . replace ( / & q u o t ; / 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 ( / & q u o t ; / g, '"' ) ;
629636} ;
630637
631638/**
0 commit comments