Skip to content

Instantly share code, notes, and snippets.

@electerious
Last active January 24, 2017 09:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electerious/a3ede10f166eef26a53e to your computer and use it in GitHub Desktop.
Save electerious/a3ede10f166eef26a53e to your computer and use it in GitHub Desktop.
html = (literalSections, ...substs) => {
// Use raw literal sections: We don’t want
// backslashes (\n etc.) to be interpreted
let raw = literalSections.raw,
let result = ''
substs.forEach((subst, i) => {
// Retrieve the literal section preceding
// the current substitution
let lit = raw[i]
// If the substitution is preceded by a dollar sign,
// we escape special characters in it
if (lit.slice(-1)==='$') {
subst = escapeHTML(subst)
lit = lit.slice(0, -1)
}
result += lit
result += subst
})
// Take care of last literal section
// (Never fails, because an empty template string
// produces one literal section, an empty string)
result += raw[raw.length-1]
return result
}
@electerious
Copy link
Author

Requirements:

Example:

let htmlString = `<script>alert('XSS')</script>`

let output = html`
  <p>$${ htmlString }</p>
  ${ htmlString }
`

console.log(output)

Output:

<p>&lt;script&gt;alert(&#039;Hello XSS&#039;)&lt;/script&gt;</p>
<script>alert('Hello XSS')</script>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment