注意:
在編寫html時,經常需要轉義,才能正常顯示在頁面上。
並且,還可以防止xss。
解決方案:
一, 使用正則:
使用正則轉碼:
var value = document.getElementById('input').value.trim(); //對用戶輸入進行轉義
value = value.replace(/&/g,"&"); value = value.replace(/</g,"<"); value = value.replace(/>/g,">"); value = value.replace(/ /g," ");
value = value.replace(/"/g,'"');
使用正則解碼:
var value = e.target.innerText; // value = decodeURIComponent(value);
value = value.replace(/&/g,"&"); value = value.replace(/</g,"<"); value = value.replace(/>/g,">"); value = value.replace(/ /g," "); value = value.replace(/"/g,"'");
方法二:使用瀏覽器自帶的。詳情異步:https://www.cnblogs.com/GumpYan/p/7883133.html
