How to decode unicode HTML by JavaScript?

2020-05-27 19:35发布

问题:

How to use JavaScript to decode from:

\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!

回答1:

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>

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



回答2:

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

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

Output:

'<b>string</b>'