14

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!

2 Answers 2

30

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>'
Sign up to request clarification or add additional context in comments.

1 Comment

Since I just happened on this again, here's a more modern version: JSON.parse(`"${x}"`)
13
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.

5 Comments

Note that the string was already <b>string</b>. decodeURIComponent did nothing. jsfiddle.net/ZAXux. Here's a jsfiddle to show decodeURIComponent does nothing when the string is literally \u003cb\u003estring\u003c/b\u003e jsfiddle.net/ZAXux/1
@Esailija Your second jsFiddle has an extra "\" character. As for your first statement, what do you mean "does nothing"?
In javascript you need to write "\\u" to get \u literally. If you don't escape the backslash and write "\u" , it is interpreted as a Unicode escape sequence. By nothing I mean it doesn't do anything and it can be removed without any change as the first jsfiddle shows. So: decodeURIComponent('\u003cb\u003estring\u003c/b\u003e'); === '\u003cb\u003estring\u003c/b\u003e'
@Esailija You are 100% right...I feel really stupid right now. Thank you for taking the time to explain that to me. I'll remove this answer.
If the string contains \u003c literally, then removing \ will just yield u003c. The escape sequences are only meaningful when something is parsing them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.