Skip to content

Instantly share code, notes, and snippets.

@codesorter2015
Forked from Rob--W/escaopeHTMLTag.js
Created April 11, 2018 10:18
Show Gist options
  • Select an option

  • Save codesorter2015/8b5f9f773577e438b29aa97285271cd3 to your computer and use it in GitHub Desktop.

Select an option

Save codesorter2015/8b5f9f773577e438b29aa97285271cd3 to your computer and use it in GitHub Desktop.

Revisions

  1. @Rob--W Rob--W created this gist Nov 14, 2016.
    28 changes: 28 additions & 0 deletions escaopeHTMLTag.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    /* Example:
    var someUnsafeStr = '<img>';
    var result = escapeHTMLTag`<input value="${someUnsafeStr}">`;
    console.log(result); // <input value="&lt;img&gt;">
    // Questions? rob {at} robwu.nl
    // */

    function escapeHTML(str) {
    // Note: string cast using String; may throw if `str` is non-serializable, e.g. a Symbol.
    // Most often this is not the case though.
    return String(str)
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;').replace(/'/g, '&#39;')
    .replace(/</g, '&lt;').replace(/>/g, '&gt;');
    }

    // A tag for template literals that escapes any value as HTML.
    function escapeHTMLTag(strings, ...values) {
    let results = [];
    for (let i = 0; i < strings.length; ++i) {
    results.push(strings[i]);
    if (i < values.length) { // values[strings.length-1] can be undefined
    results.push(escapeHTML(values[i]));
    }
    }
    return results.join('');
    }