如何通过 JavaScript 解码 unicode HTML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15929686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:38:59  来源:igfitidea点击:

How to decode unicode HTML by JavaScript?

javascriptunicodedecode

提问by Tuyen Pham

How to use JavaScript to decode from:

如何使用 JavaScript 解码:

\u003cb\u003estring\u003c/b\u003e

to

<b>string</b>

(I searched in internet, there are some site with same question, such as: Javascript html decoding
or How to decode HTML entities
but it dont have same encode fomat)
Thank you very much!

(我在互联网上搜索,有一些网站有相同的问题,例如: Javascript html 解码
如何解码 HTML 实体
但它没有相同的编码格式
非常感谢!

回答by Joe Hildebrand

This is a dup of How do I decode a string with escaped unicode?. One of the answers given there should work:

这是如何使用转义的 unicode 解码字符串的副本?. 那里给出的答案之一应该有效:

var x = '\u003cb\u003estring\u003c/b\u003e';
JSON.parse('"' + x + '"')

Output:

输出:

'<b>string</b>'

回答by Brad M

decodeURIComponent('\u003cb\u003estring\u003c/b\u003e');

//  "<b>string</b>"

Edit - I would delete the above answer if I could.

编辑 - 如果可以的话,我会删除上述答案。

The original question is a bit ambiguous.

最初的问题有点模棱两可。

console.log('\u003cb\u003estring\u003c/b\u003e');will already yield <b>string</b>

console.log('\u003cb\u003estring\u003c/b\u003e');将已经屈服 <b>string</b>

If the \characters are escaped, then a replacement method could be used to replace \\with just \, thus allowing the proper Unicode escape sequence.

如果\字符被转义,则可以使用替换方法\\仅替换为\,从而允许正确的 Unicode 转义序列。