javascript 把html代码转换为实体的函数 ?

结果不对

function htmlEscape(text){
return text.replace(/[<>"&]/g,function(match,pos,originalText){
switch(match){
case "<":return "<";
case ">":return ">";
case "&":return "&";
case "\"":return """;
}
});
}

var test=htmlEscape("<p>something.</p>")

document.write(test)
百度把lt gt amp这些转换了,return后面是实体

30秒到达战场
浏览 1164回答 3
3回答

月关宝盒

应该这么写:function htmlEntities(str) {return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');}

猛跑小猪

你应该是需要html编码和解码,我这里有个比较巧妙的方式1234567891011121314151617181920212223//js版//Html编码获取Html转义实体&nbsp;function&nbsp;htmlEncode(value)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;e&nbsp;=&nbsp;document.createElement('div');&nbsp;&nbsp;&nbsp;&nbsp;e.innerText&nbsp;=&nbsp;value;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;e.innerHTML;}//Html解码获取Html实体&nbsp;function&nbsp;htmlDecode(value)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;e&nbsp;=&nbsp;document.createElement('div');&nbsp;&nbsp;&nbsp;&nbsp;e.innerHTML&nbsp;=&nbsp;value;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;e.innerText;}&nbsp;//jQuery版//Html编码获取Html转义实体&nbsp;function&nbsp;htmlEncode(value){&nbsp;&nbsp;return&nbsp;$('<div/>').text(value).html();&nbsp;}&nbsp;//Html解码获取Html实体&nbsp;function&nbsp;htmlDecode(value){&nbsp;&nbsp;return&nbsp;$('<div/>').html(value).text();&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Vue.js