JavaScript-解码URI以呈现为HTML

JavaScript - decodeURI to render as HTML

本文关键字:HTML 解码 URI JavaScript-      更新时间:2023-09-26

我遇到了一个小问题,一直困扰着我,似乎找不到有效的解决方案。我有一个字符串,它来自以下格式的xml文档。

var str="<p><a href="http://antwrp.gsfc.nasa.gov/apod/ap131120.html"><img src="http://antwrp.gsfc.nasa.gov/apod/calendar/S_131120.jpg" align="left" alt="What are black hole jets made of?" border="0" /></a> What are black & hole jets made of?</p><br clear="all"/>";

我用过

var dec = decodeURI(str);

我希望将输出呈现为HTML,而不会看到下面的输出。

<p><a href="http://antwrp.gsfc.nasa.gov/apod/ap131120.html"><img src="http://antwrp.gsfc.nasa.gov/apod/calendar/S_131120.jpg" align="left" alt="What are black hole jets made of?" border="0" /></a> What are black &amp; hole jets made of?</p><br clear="all"/>

我已经尝试用将这些解码后的数据发送到HTML文档

document.write(dec)

document.getElementById("output").innerHTML=dec; 

您可以手动替换所有实体

function unescape(str){
    return str.replace(/&lt;/g, "<")
              .replace(/&gt;/g, ">")
              .replace(/&quot;/g, '"')
              .replace(/&amp;/g, "&");
}
var str="&lt;p&gt;&lt;.../&gt;";
document.getElementById("output").innerHTML = unescape(str);  

您混淆了URL编码和html/xml实体。它们是两种不同的编码方法。例如,在URL编码中,<被编码为%3C,但对于实体,它是&lt;

如果运行console.log(decodeURI(str)),您会注意到像&quot这样的大多数东西都保持不变,因为decodeURI()不应该解码html实体。

为了解决这个问题,您可以让xml返回正确的URL编码:

var str="%3Cp%3E%3Ca href=%22http://antwrp.gsfc.nasa.gov/apod/ap131120.html%22%3E%3Cimg src=%22http://antwrp.gsfc.nasa.gov/apod/calendar/S_131120.jpg%22align=%22left%22alt=%22What are black hole jets made of?%22border=%220%22/%3E%3C/a%3E What are black hole jets made of?%3C/p%3E%3Cbr clear=%22all%22/%3E";

或者,您可以使用一段Javascript函数来解码您现在拥有的实体。

演示:http://jsfiddle.net/Ly4ZR/

有一个JavaScript库可以帮助您做到这一点。看看这个Fiddle。

var str="&lt;p&gt;&lt;a href=&quot;http://antwrp.gsfc.nasa.gov/apod/ap131120.html&quot;&gt;&lt;img src=&quot;http://antwrp.gsfc.nasa.gov/apod/calendar/S_131120.jpg&quot; align=&quot;left&quot; alt=&quot;What are black hole jets made of?&quot; border=&quot;0&quot; /&gt;&lt;/a&gt; What are black &amp;amp; hole jets made of?&lt;/p&gt;&lt;br clear=&quot;all&quot;/&gt;";
$("#output").html(_.unescape(str));