Javascript decodeURI(Component) 格式错误的 uri 异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9064536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript decodeURI(Component) malformed uri exception
提问by Christian
I entered the following in Chrome's console:
我在 Chrome 的控制台中输入了以下内容:
decodeURIComponent('a%AFc');
Instead of resulting to a0xAFc
, it caused a URIError exception (malformed uri).
相反,导致到的a0xAFc
,就引起了异常的URIError(畸形URI)。
I've heard several excuses why this may be possible, but what I don't understand is why?
我听过几个借口为什么这可能是可能的,但我不明白为什么?
The decodeURIComponent()
function in particular is supposed to decode data, not verify the URI.
该decodeURIComponent()
函数尤其应该解码数据,而不是验证 URI。
回答by Juicy Scripter
%AF
is not a character on his own but part of Unicode sequence (MACRON - %C2%AF
).
%AF
本身不是一个字符,而是 Unicode 序列 ( MACRON - %C2%AF
) 的一部分。
%AF
wasn't produced by encodeURIComponent
but something like escape
, so it can be decoded by unescape
.
%AF
不是由encodeURIComponent
但类似的东西产生的escape
,所以它可以被解码unescape
。
What you probably need is decodeURIComponent('%C2%AF')
你可能需要的是 decodeURIComponent('%C2%AF')
回答by Nelles
This may or may not apply to someone else's situation but this is what did it for me so I thought I would share. I upload and download lots of text files to a custom CMS.
the '%' sign in the source codewas wreaking havoc for me.
这可能适用于也可能不适用于其他人的情况,但这就是为我所做的,所以我想我会分享。我将大量文本文件上传和下载到自定义 CMS。源代码中
的 “%”符号对我造成了严重破坏。
// send to server
content = content.toString().replace(/%/g,'~~pct~~'); // ~~pct~~ <-made up replacement
content = encodeURI(content);
// get back from server / database
content = decodeURI(content);
content = content.toString().replace(/~~pct~~/g,'%'); // globally restore '%'