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, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
 
    // Don't escape special characters in the template.
    s += templateData[i]
  }
  return s
}

let sender = '<script>alert("abc")&nbsp;</script>' // 惡意代碼
let message = SaferHTML`<p>${sender} has sent you a message.</p>`
console.log(message)    // <p>&lt;script&gt;alert("abc")&amp;nbsp;&lt;/script&gt; has sent you a message.</p>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM