javascriptdecodeurldecode

How do I decode a string with escaped unicode?


I'm not sure what this is called so I'm having trouble searching for it. How can I decode a string with unicode from http\u00253A\u00252F\u00252Fexample.com to http://example.com with JavaScript? I tried unescape, decodeURI, and decodeURIComponent so I guess the only thing left is string replace.

EDIT: The string is not typed, but rather a substring from another piece of code. So to solve the problem you have to start with something like this:

var s = 'http\\u00253A\\u00252F\\u00252Fexample.com';

I hope that shows why unescape() doesn't work.


Solution

  • Edit (2017-10-12):

    @MechaLynx and @Kevin-Weber note that unescape() is deprecated from non-browser environments and does not exist in TypeScript. decodeURIComponent is a drop-in replacement. For broader compatibility, use the below instead:

    decodeURIComponent(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
    > 'http://example.com'
    

    Original answer:

    unescape(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
    > 'http://example.com'
    

    You can offload all the work to JSON.parse