damus.io

damus.io website
git clone git://jb55.com/damus.io
Log | Files | Refs | README | LICENSE

safe-html.js (897B)


      1 // https://github.com/AntonioVdlC/html-template-tag
      2 
      3 const chars = {
      4   "&": "&",
      5   ">": ">",
      6   "<": "&lt;",
      7   '"': "&quot;",
      8   "'": "&#39;",
      9   "`": "&#96;",
     10 };
     11 
     12 // Dynamically create a RegExp from the `chars` object
     13 const re = new RegExp(Object.keys(chars).join("|"), "g");
     14 
     15 // Return the escaped string
     16 function escape(str) {
     17   return String(str).replace(re, (match) => chars[match]);
     18 }
     19 
     20 function html(
     21   literals,
     22   ...substs
     23 ) {
     24   return literals.raw.reduce((acc, lit, i) => {
     25     let subst = substs[i - 1];
     26     if (Array.isArray(subst)) {
     27       subst = subst.join("");
     28     } else if (literals.raw[i - 1] && literals.raw[i - 1].endsWith("$")) {
     29       // If the interpolation is preceded by a dollar sign,
     30       // substitution is considered safe and will not be escaped
     31       acc = acc.slice(0, -1);
     32     } else {
     33       subst = escape(subst);
     34     }
     35 
     36     return acc + subst + lit;
     37   });
     38 }