13

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!

Community
  • 1
  • 1
NoName
  • 7,940
  • 13
  • 56
  • 108

2 Answers2

28

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>'
Community
  • 1
  • 1
Joe Hildebrand
  • 10,354
  • 2
  • 38
  • 48
12
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.

Brad M
  • 7,857
  • 1
  • 23
  • 40
  • Note that the string was already `string`. `decodeURIComponent` did nothing. http://jsfiddle.net/ZAXux/. Here's a jsfiddle to show `decodeURIComponent` does nothing when the string is literally `\u003cb\u003estring\u003c/b\u003e` http://jsfiddle.net/ZAXux/1/ – Esailija Apr 10 '13 at 23:41
  • @Esailija Your second jsFiddle has an extra "\" character. As for your first statement, what do you mean "does nothing"? – Brad M Apr 11 '13 at 03:07
  • 1
    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 Apr 11 '13 at 08:58
  • @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. – Brad M Apr 11 '13 at 13:55
  • 1
    If the string contains `\u003c` literally, then removing \ will just yield `u003c`. The escape sequences are only meaningful when something is parsing them. – Esailija Apr 11 '13 at 15:31