« get me outta code hell

html, language: html.escape() - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/src/html.js
diff options
context:
space:
mode:
author(quasar) nebula <qznebula@protonmail.com>2025-10-20 13:02:53 -0300
committer(quasar) nebula <qznebula@protonmail.com>2025-10-20 13:07:03 -0300
commit4f69806230d69f215a873479f1728cc2fe5ebb46 (patch)
treeffa715fd3f3c925a4b0916c81ff2ee74903adea0 /src/html.js
parentf88043e17125affb9bb8e37d5b58e5a65e9c89d7 (diff)
html, language: html.escape()
Diffstat (limited to 'src/html.js')
-rw-r--r--src/html.js35
1 files changed, 17 insertions, 18 deletions
diff --git a/src/html.js b/src/html.js
index eb783ac6..0a868ebd 100644
--- a/src/html.js
+++ b/src/html.js
@@ -359,6 +359,22 @@ export function normalize(content) {
   return Tag.normalize(content);
 }
 
+export function escape(string, {attribute = false} = {}) {
+  // https://html.spec.whatwg.org/multipage/parsing.html#escapingString
+
+  string = string
+    .replaceAll('&', '&amp;')
+    .replaceAll('\u00a0', '&nbsp;')
+    .replaceAll('<', '&lt;')
+    .replaceAll('>', '&gt;');
+
+  if (attribute) {
+    string = string.replaceAll('"', '&quot;');
+  }
+
+  return string;
+}
+
 export class Tag {
   #tagName = '';
   #content = null;
@@ -1343,7 +1359,7 @@ export class Attributes {
       attributeKeyValues
         .map(([key, value]) => {
           const keyPart = key;
-          const escapedValue = this.#escapeAttributeValue(value);
+          const escapedValue = escape(value.toString(), {attribute: true});
           const valuePart =
             (color
               ? colors.green(`"${escapedValue}"`)
@@ -1419,23 +1435,6 @@ export class Attributes {
     }
   }
 
-  #escapeAttributeValue(value) {
-    // https://html.spec.whatwg.org/multipage/parsing.html#escapingString
-
-    // assumes the containing attribute value token is written
-    // with double quotes
-
-    value = value
-      .toString()
-      .replaceAll('&', '&amp;')
-      .replaceAll('\u00a0', '&nbsp;')
-      .replaceAll('<', '&lt;')
-      .replaceAll('>', '&gt;')
-      .replaceAll('"', '&quot;');
-
-    return value;
-  }
-
   static parse(string) {
     const attributes = Object.create(null);