Skip to content

Instantly share code, notes, and snippets.

@willbroderick
Last active June 16, 2021 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willbroderick/ddf291aa6b038ca704b392d256281973 to your computer and use it in GitHub Desktop.
Save willbroderick/ddf291aa6b038ca704b392d256281973 to your computer and use it in GitHub Desktop.
Escape/encode strings used to build HTML in a template literal
/**
* 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