Last active
June 16, 2021 06:37
-
-
Save willbroderick/ddf291aa6b038ca704b392d256281973 to your computer and use it in GitHub Desktop.
Escape/encode strings used to build HTML in a template literal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Use with template literals to build HTML with correct escaping. | |
* | |
* Example: | |
* | |
* const tve = createTemplateVariableEncoder(); | |
* tve.add('dataValue', 'What is "this"?', 'attribute'); | |
* tve.add('title', 'Title & Heading', 'html'); | |
* tve.add('richText', '<p>Content to show</p>', 'raw'); | |
* | |
* const template = ` | |
* <div data-value="${tve.values.dataValue}"> | |
* <h1>${tve.values.title}</h1> | |
* <div class="rte">${tve.values.richText}</div> | |
* </div> | |
* `; | |
*/ | |
function createTemplateVariableEncoder() { | |
return { | |
utilityElement: document.createElement('div'), | |
values: {}, | |
/** | |
* Add a new value to sanitise. | |
* @param {String} key - key used to retrieve this value | |
* @param {String} value - the value to encode and store | |
* @param {String} type - possible values: [attribute, html, raw] - the type of encoding to use | |
*/ | |
add: function(key, value, type){ | |
switch(type) { | |
case 'attribute': | |
this.utilityElement.innerHTML = ''; | |
this.utilityElement.setAttribute('util', value); | |
this.values[key] = this.utilityElement.outerHTML.match(/util="([^"]*)"/)[1]; | |
break; | |
case 'html': | |
this.utilityElement.innerText = value; | |
this.values[key] = this.utilityElement.innerHTML; | |
break; | |
case 'raw': | |
this.values[key] = value; | |
break; | |
default: | |
throw `Type '${type}' not handled`; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment