我可以在javascript中转义html特殊字符吗?我希望通过javascript函数将文本显示为HTML。如何在JS中转义html特殊字符?有API吗?
3 回答
拉丁的传说
TA贡献1789条经验 获得超8个赞
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
偶然的你
TA贡献1841条经验 获得超3个赞
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>'>
添加回答
举报
0/150
提交
取消
