Created
February 19, 2016 14:44
-
-
Save trevorgk/8f5ae15976f4cc44f7f6 to your computer and use it in GitHub Desktop.
Useful and clever regex worth understanding, taken from https://developers.google.com/web/updates/2015/01/ES6-Template-Strings?hl=en
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 | |
var util = (function () { | |
// Thanks to Andrea Giammarchi | |
var | |
reEscape = /[&<>'"]/g, | |
reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g, | |
oEscape = { | |
'&': '&', | |
'<': '<', | |
'>': '>', | |
"'": ''', | |
'"': '"' | |
}, | |
oUnescape = { | |
'&': '&', | |
'&': '&', | |
'<': '<', | |
'<': '<', | |
'>': '>', | |
'>': '>', | |
''': "'", | |
''': "'", | |
'"': '"', | |
'"': '"' | |
}, | |
fnEscape = function (m) { | |
return oEscape[m]; | |
}, | |
fnUnescape = function (m) { | |
return oUnescape[m]; | |
}, | |
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 | |
function html(pieces) { | |
var result = pieces[0]; | |
var substitutions = [].slice.call(arguments, 1); | |
for (var i = 0; i < substitutions.length; ++i) { | |
result += util.escape(substitutions[i]) + pieces[i + 1]; | |
} | |
return result; | |
} | |
var username = "Domenic Denicola"; | |
var tag = "& is a fun tag"; | |
console.log(html`<b>${username} says</b>: "${tag}"`); | |
//=> <b>Domenic Denicola says</b>: "& is a fun tag" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment