如何转义HTML但不转义字符实体?

时间:2017-04-16 16:50:39

标签: javascript html html-escape-characters

我必须转义任意字符串,然后分配给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”?

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

首先是unescape,所以将&amp;替换为&,然后转义。

示例:

&#13;
&#13;
function unescapeHtml(unsafe) {
    return unsafe
         .replace(/&amp;/g, "&")
         .replace(/&lt;/g, "<")
         .replace(/&gt;/g, ">")
         .replace(/&quot;/g, '"')
         .replace(/&#039;/g, "'")
      
}

function escapeHtml(unsafe) {
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
}
function setText(id, text){

   document.getElementById(id).innerHTML = escapeHtml(unescapeHtml(text))
} 

var str1 = "A &amp; B & C";
var str2 = "A &gt; B > C";
var str3 = "A&amp;B&amp;C"
var str4 = "A&quot;B&quot; C &quot;"
   
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;
&#13;
&#13;

答案 1 :(得分:0)

var str1 = "A &amp; B & C";
var str2 = "A &gt; B > C";
var str3 = "A &amp; B &amp; C &gt; D &lt; X";

str1 = str1.replace(/\&amp\;/g, '&');
str2 = str2.replace(/\&gt\;/g, '>');
str3 = str3.replace(/\&amp\;/g, '&').replace(/\&gt\;/g, '>').replace(/\&lt\;/g, '<');

console.log(str1);
console.log(str2);
console.log(str3);

https://jsfiddle.net/fkherav8/2/