javascript decodeURIComponent 抛出错误“URI 格式错误”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28063750/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:21:28  来源:igfitidea点击:

decodeURIComponent throwing an error 'URI malformed'

javascriptjqueryjquery-pluginsurldecode

提问by vimal1083

As unescapehas been deprecated I have chosen decodeURIComponent, but it doesn't work as expected . decodeURIComponentcant decode the following URI component

由于unescape已弃用,我选择了decodeURIComponent,但它没有按预期工作。decodeURIComponent无法解码以下 URI 组件

Coast%20Guard%20Academy%20to%20hold%20annual%20Women%92s%20%91Leadhership%92%20event

While decoding the above string decodeURIComponent throws an error, which blocks the remaining javascript execution.

在解码上面的字符串时,decodeURIComponent 会抛出一个错误,这会阻止剩余的 javascript 执行。

Is there is any solution to fix this ?

有没有办法解决这个问题?

回答by Phylogenesis

The %91and %92characters were encoded using an ANSI codepage. decodeURIComponent()expects the string to have been encoded as UTF-8:

%91%92使用ANSI代码页的字符进行编码。decodeURIComponent()期望字符串被编码为 UTF-8

The decodeURIComponentfunction computes a new version of a URI in which each escape sequence and UTF-8 encoding of the sort that might be introduced by the encodeURIComponentfunction is replaced with the character that it represents.

decodeURIComponent函数计算一个新版本的 URI,其中每个转义序列和该encodeURIComponent函数可能引入的排序的 UTF-8 编码都被替换为它所代表的字符。

The two quotes should be encoded as %E2%80%98and %E2%80%99.

这两个引号应编码为%E2%80%98and %E2%80%99