解码其中包含特殊HTML实体的字符串的正确方法是什么? [英] What's the right way to decode a string that has special HTML entities in it?

查看:115
本文介绍了解码其中包含特殊HTML实体的字符串的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我从服务请求中获得了一些JSON,如下所示:

Say I get some JSON back from a service request that looks like this:

{
    "message": "We're unable to complete your request at this time."
}

我不确定为什么该撇号是这样编码(' );所有我知道的是我想解码它。

I'm not sure why that apostraphe is encoded like that ('); all I know is that I want to decode it.

这是一种使用jQuery的方法,它突然出现在我脑海中:

Here's one approach using jQuery that popped into my head:

function decodeHtml(html) {
    return $('<div>').html(html).text();
}

但这似乎(非常)hacky。什么是更好的方式?是否有正确的方式?

That seems (very) hacky, though. What's a better way? Is there a "right" way?

推荐答案

这是我最喜欢的HTML字符解码方式。使用此代码的优点是标签也会被保留。

This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

示例:http://jsfiddle.net/k65s3/

输入:

Entity:&nbsp;Bad attempt at XSS:<script>alert('new\nline?')</script><br>

输出:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>

这篇关于解码其中包含特殊HTML实体的字符串的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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