我必须转义任意字符串,然后分配给innerHTML。
但字符串可能已包含字符实体,例如
var str1 = "A & B & C";
var str2 = "A > B > C";
var str3 = "A&qout;B&qout; C &qout;";
我想要
A & B & C
A < B & < C
A"B" C "
问题是如何逃避“&amp;”但是不要逃避“&amp; in other characters entities”?
感谢您的帮助!
答案 0 :(得分:0)
首先是unescape,所以将&
替换为&
,然后转义。
示例:
function unescapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, '"')
.replace(/'/g, "'")
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function setText(id, text){
document.getElementById(id).innerHTML = escapeHtml(unescapeHtml(text))
}
var str1 = "A & B & C";
var str2 = "A > B > C";
var str3 = "A&B&C"
var str4 = "A"B" C ""
setText("container1", str1);
setText("container2", str2);
setText("container3", str3);
setText("container4", str4);
&#13;
<div id="container1"></div>
<div id="container2"></div>
<div id="container3"></div>
<div id="container4"></div>
&#13;
答案 1 :(得分:0)
var str1 = "A & B & C";
var str2 = "A > B > C";
var str3 = "A & B & C > D < X";
str1 = str1.replace(/\&\;/g, '&');
str2 = str2.replace(/\>\;/g, '>');
str3 = str3.replace(/\&\;/g, '&').replace(/\>\;/g, '>').replace(/\<\;/g, '<');
console.log(str1);
console.log(str2);
console.log(str3);