在Javascript中解压HTML实体? [英] Unescape HTML entities in Javascript?

查看:92
本文介绍了在Javascript中解压HTML实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些与XML-RPC后端通信的Javascript代码。
XML-RPC返回以下形式的字符串:

 < img src ='myimage.jpg'> 

但是,当我使用Javascript将字符串插入到HTML中时,它们会以字面形式显示。我看不到图像,我字面上看到字符串:

 < img src ='myimage.jpg'> 

我的猜测是HTML正在通过XML-RPC频道进行转义。



如何在Javascript中解开字符串?我尝试了这个页面上的技术,失败: http://paulschreiber.com/blog/2008/09/20/javascript-how-to-unescape-html-entities/



其他什么方法来诊断问题?

解决方案

我使用以下方法:

  function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
//处理空输入的情况
return e.childNodes.length === 0? :e.childNodes [0] .nodeValue;
}

htmlDecode(& lt; img src ='myimage.jpg'& gt);
//返回< img src ='myimage.jpg'>

基本上我以编程方式创建了一个DOM元素,将编码的HTML分配给其innerHTML,并从在innerHTML插入上创建的文本节点。由于它只是创建一个元素,而是从不添加它,所以没有网站HTML被修改。



它将工作跨浏览器(包括旧浏览器)并接受所有的 HTML Character Entities



编辑:这个代码的旧版本在IE上没有空白的输入,证明了 here on jsFiddle (在IE中查看)。以上版本适用于所有输入。



更新:出现此功能不适用于大型字符串,并且还会引入安全漏洞,请参阅注释。


I have some Javascript code that communicates with an XML-RPC backend. The XML-RPC returns strings of the form:

<img src='myimage.jpg'>

However, when I use the Javascript to insert the strings into HTML, they render literally. I don't see an image, I literally see the string:

<img src='myimage.jpg'>

My guess is that the HTML is being escaped over the XML-RPC channel.

How can I unescape the string in Javascript? I tried the techniques on this page, unsuccessfully: http://paulschreiber.com/blog/2008/09/20/javascript-how-to-unescape-html-entities/

What are other ways to diagnose the issue?

解决方案

I use the following method:

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  // handle case of empty input
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}

htmlDecode("&lt;img src='myimage.jpg'&gt;"); 
// returns "<img src='myimage.jpg'>"

Basically I create a DOM element programmatically, assign the encoded HTML to its innerHTML and retrieve the nodeValue from the text node created on the innerHTML insertion. Since it just creates an element but never adds it, no site HTML is modified.

It will work cross-browser (including older browsers) and accept all the HTML Character Entities.

EDIT: The old version of this code did not work on IE with blank inputs, as evidenced here on jsFiddle (view in IE). The version above works with all inputs.

UPDATE: appears this doesn't work with large string, and it also introduces a security vulnerability, see comments.

这篇关于在Javascript中解压HTML实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆