将清理过的html转换回可显示的html [英] Converting sanitised html back to displayable html

查看:57
本文介绍了将清理过的html转换回可显示的html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



基本上我得到的是这样的:

 & lt; div class =someclass& gt;& lt; blockquote& gt; 
& lt; p& gt;这里的东西。& lt; / p& gt;
& lt; / blockquote& gt;

等等。因此,如果我尝试显示它,则显示为

 < div class =someclass>< blockquote> < p>此处< / p> < / BLOCKQUOTE> 

我想要的是在显示前将其转换为正确的html,以便内容正确显示标签。



使用javascript执行此操作的最简单方法是什么?



只需在此注意我正在Adobe AIR中工作。所以我没有任何其他的选择。你可以创建一个元素,将编码的HTML分配给它的innerHTML,并检索

 函数htmlDecode(输入){
var e = document.createElement ( 'DIV');
e.innerHTML = input;
return e.childNodes [0] .nodeValue;
}

htmlDecode('& lt; div class =someclass& gt;& lt; blockquote& gt;& lt; p& gt;& quot; '+
'something& nbsp;& nbsp;& lt; / p& gt; Q& lt; / blockquote& gt;')

//返回:
//< div class =someclass>< blockquote>< p>somethinghere。< / p> Q< / blockquote>

请注意,此方法应与所有 HTML字符实体


I'm getting html data from a database which has been sanitised.

Basically what I'm getting is something like this:

&lt;div class="someclass"&gt;&lt;blockquote&gt;
  &lt;p&gt;something here.&lt;/p&gt;
&lt;/blockquote&gt;

And so on. So if I try to display it, it is displaying as

<div class="someclass"><blockquote> <p>something here</p> </blockquote>

What I want is to convert it to proper html before displaying, so that the content displays properly, without the tags.

What's the easiest way to do this using javascript?

Just want to note here that I'm working with in Adobe AIR. So I don't have any alternatives.

解决方案

You could create an element, assign the encoded HTML to its innerHTML and retrieve the nodeValue from the text node created on the insertion.

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes[0].nodeValue;
}

htmlDecode('&lt;div class="someclass"&gt;&lt;blockquote&gt; &lt;p&gt;&quot; ' +
           'something&quot;&nbsp;here.&lt;/p&gt;Q&lt;/blockquote&gt;')

// returns :
// "<div class="someclass"><blockquote> <p>"something" here.</p>Q</blockquote>"

Note that this method should work with all the HTML Character Entities.

这篇关于将清理过的html转换回可显示的html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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