JavaScript - decodeURI以呈现为HTML

时间:2013-11-22 09:20:24

标签: javascript

我有一个问题一直困扰着我,我似乎无法找到一个有效的解决方案。我有一个字符串,它来自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; 

3 个答案:

答案 0 :(得分:1)

您可以手动替换所有实体

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);  

答案 1 :(得分:0)

您对URL encodinghtml/xml entities感到困惑。它们是两种不同的编码方法。例如,在网址编码中,<编码为%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";

或者您可以使用a piece of Javascript function解码您现在拥有的实体。

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

答案 2 :(得分:0)

有一个JavaScript Library可能会对此有所帮助。请参阅此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));
相关问题