慕工程0101907
2019-06-23 17:25:27
我可以在javascript中轉(zhuǎn)義html特殊字符嗎?我希望通過javascript函數(shù)將文本顯示為HTML。如何在JS中轉(zhuǎn)義html特殊字符?有API嗎?
3 回答

拉丁的傳說
TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超8個(gè)贊
function escapeHtml(unsafe) { return unsafe .replace(/&/g, "&") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, """) .replace(/'/g, "'"); }

偶然的你
TA貢獻(xiàn)1841條經(jīng)驗(yàn) 獲得超3個(gè)贊
function escapeHtml(html){
var text = document.createTextNode(html);
var p = document.createElement('p');
p.appendChild(text);
return p.innerHTML;
}
// Escape while typing & print result
document.querySelector('input').addEventListener('input', e => {
console.clear();
console.log( escapeHtml(e.target.value) );
});
<input style='width:90%; padding:6px;' placeholder='<b>cool</b>'>
添加回答
舉報(bào)
0/150
提交
取消