富文本信息在html展示不出,需要转码
<script>
var HtmlUtil = {
/*1.用浏览器内部转换器实现html转码*/
htmlEncode:function (html){
//1.首先动态创建一个容器标签元素,如DIV
var temp = document.createElement ("div");
//2.然后将要转换的字符串设置为这个元素的innerText(ie支持)或者textContent(旧版火狐,google支持)
(temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html);
//3.最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了
var output = temp.innerHTML;
temp = null;
return output;
},
/*2.用浏览器内部转换器实现html解码*/
htmlDecode:function (text){
//1.首先动态创建一个容器标签元素,如DIV
var temp = document.createElement("div");
//2.然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持)
temp.innerHTML = text;
//3.最后返回这个元素的innerText(ie支持)或者textContent(火狐,google支持),即得到经过HTML解码的字符串了。
var output = temp.innerText || temp.textContent;
temp = null;
return output;
},
/*3.用正则表达式实现html转码*/
htmlEncodeByRegExp:function (str){
var s = "";
if(str.length == 0) return "";
s = str.replace(/&/g,"&");
s = s.replace(/</g,"<");
s = s.replace(/>/g,">");
s = s.replace(/\s/g," ");
s = s.replace(/\'/g,"'");
s = s.replace(/\"/g,""");
return s;
},
/*4.用正则表达式实现html解码*/
htmlDecodeByRegExp:function (str){
var s = "";
if(str.length == 0) return "";
s = str.replace(/&/g,"&");
s = s.replace(/</g,"<");
s = s.replace(/>/g,">");
s = s.replace(/ /g," ");
s = s.replace(/'/g,"\'");
s = s.replace(/"/g,"\"");
return s;
}
};
// 使用举例
// 用浏览器内部转换器实现html转码
var html = " <div>'我们在哪里'</div> "
var enCodehtml = HtmlUtil.htmlEncode(html);
console.log(enCodehtml); // <div>'我们在哪里'</div>
// 用浏览器内部转换器实现html解码
var decodeHtml = HtmlUtil.htmlDecode(enCodehtml);
console.log(decodeHtml); // <div>'我们在哪里'</div>
// ————————————————————————————————————————————————————————————————
// 用正则表达式实现html转码
var html2 = "<div> winne'hello'</div>";
var RegExpEnCodehtml = HtmlUtil.htmlEncodeByRegExp(html2)
console.log(RegExpEnCodehtml); // <div> winne'hello'</div>
// 用正则表达式实现html解码
var RegExpDecodeHtml = HtmlUtil.htmlDecodeByRegExp(RegExpEnCodehtml);
console.log(RegExpDecodeHtml); // <div> winne'hello'</div>
</script>
参考:https://blog.csdn.net/m0_38134431/article/details/84950653