简体   繁体   English

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

[英]How to escape HTML but do not escape character entities?

I have to escape an arbitrary string and then assign to innerHTML.我必须转义任意字符串,然后分配给innerHTML。

But the string may has already contain character entities, like但是字符串可能已经包含字符实体,例如

var str1 = "A & B & C";
var str2 = "A > B > C";
var str3 = "A&qout;B&qout; C &qout;";

And I want to get我想得到

A & B & C 
A > B > C
A"B" C " 

The question is that how to escape "&" but do not escape "& in other character entities"?问题是如何转义“&”但不转义“其他字符实体中的&”?

First unescape, so replace &首先 unescape,所以替换& with & , and then escape.& ,然后转义。

Example:例子:

 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);
 <div id="container1"></div> <div id="container2"></div> <div id="container3"></div> <div id="container4"></div>

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/ https://jsfiddle.net/fkherav8/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM