基于安全的原因,在某些场景如果需要正常的显示 HTML 及 XML 标签,必须对标签进行转义和反转义。有两种方案
/**
* 把html转义成HTML实体字符
*/
function HTMLEncode(html) {
var temp = document.createElement("div");
(temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
var output = temp.innerHTML;
temp = null;
return output;
}
/**
* 转义字符还原成html字符
*/
function HTMLDecode(text) {
var temp = document.createElement("div");
temp.innerHTML = text;
var output = temp.innerText || temp.textContent;
temp = null;
return output;
}
/**
* 把html转义成HTML实体字符
*/
function htmlEncode(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, "'"); //IE下不支持实体名称
s = s.replace(/\"/g, """);
return s;
}
/**
* 转义字符还原成html字符
*/
function htmlRestore(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;
}
专业提供WordPress主题安装、深度汉化、加速优化等各类网站建设服务,详询在线客服!