如何使用转义的unicode解码字符串? [英] How do I decode a string with escaped unicode?
问题描述
我不确定这是什么,所以我在搜索时遇到了麻烦。如何解码带有unicode的字符串,从 http\\\%3A\\\%2F\\\%2Fexample.com
到 http://example.com
使用JavaScript?我试过 unescape
, decodeURI
和 decodeURIComponent
所以我猜唯一剩下的就是字符串替换。
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.
编辑:字符串不是键入的,而是来自另一段代码的子字符串。所以要解决这个问题,你必须从这样的事情开始:
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';
我希望这说明为什么unescape()不起作用。
I hope that shows why unescape() doesn't work.
推荐答案
原始答案:
unescape(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
> 'http://example.com'
您可以将所有工作卸载到 JSON.parse
You can offload all the work to JSON.parse
编辑(2017-10-12):
@MechaLynx和@ Kevin-Weber注意, unescape()
在非浏览器环境中已弃用,在TypeScript中不存在。 decodeURIComponent
是替代品。为了获得更广泛的兼容性,请使用以下代码:
@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'
这篇关于如何使用转义的unicode解码字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!