es6标签模板转义html
function SaferHTML(templateData) {
let s = templateData[0]
for (let i = 1; i < arguments.length; i++) {
let arg = String(arguments[i])
// Escape special characters in the substitution.
s += arg.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
// Don't escape special characters in the template.
s += templateData[i]
}
return s
}
let sender = '<script>alert("abc") </script>' // 恶意代码
let message = SaferHTML`<p>${sender} has sent you a message.</p>`
console.log(message) // <p><script>alert("abc")&nbsp;</script> has sent you a message.</p>
一点、一点才能到达彼岸