Created
May 21, 2017 10:09
-
-
Save bethrezen/2a9584776f40cafca794b90e429daa0a to your computer and use it in GitHub Desktop.
es6 template tag for html escaping
This file contains hidden or 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
| // HTML Escape helper utility | |
| const util = (function () { | |
| // Thanks to Andrea Giammarchi | |
| const reEscape = /[&<>'"]/g; | |
| const reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g; | |
| const oEscape = { | |
| '&': '&', | |
| '<': '<', | |
| '>': '>', | |
| '\'': ''', | |
| '"': '"' | |
| }; | |
| const oUnescape = { | |
| '&': '&', | |
| '&': '&', | |
| '<': '<', | |
| '<': '<', | |
| '>': '>', | |
| '>': '>', | |
| ''': '\'', | |
| ''': '\'', | |
| '"': '"', | |
| '"': '"' | |
| }; | |
| const fnEscape = function (m) { | |
| return oEscape[m]; | |
| }; | |
| const fnUnescape = function (m) { | |
| return oUnescape[m]; | |
| }; | |
| const replace = String.prototype.replace; | |
| return (Object.freeze || Object)({ | |
| escape: function escape(s) { | |
| return replace.call(s, reEscape, fnEscape); | |
| }, | |
| unescape: function unescape(s) { | |
| return replace.call(s, reUnescape, fnUnescape); | |
| } | |
| }); | |
| }()); | |
| // Tagged template function | |
| const html = (pieces, ...substitutions) => { | |
| let result = pieces[0]; | |
| for (let i = 0; i < substitutions.length; ++i) { | |
| result += util.escape(substitutions[i]) + pieces[i + 1]; | |
| } | |
| return result; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment