我有一个Web服务,可以接收来自不同客户端的数据。其中一些发送使用escape()编码的数据,而其他人使用encodeURIComponent()。有没有办法检测用于转义数据的编码?
答案 0 :(得分:12)
这对服务器端没有帮助,但在客户端我使用javascript异常来检测url编码是否产生了ISO Latin或UTF8编码。
decodeURIComponent
会在无效的UTF8序列上抛出异常。
try {
result = decodeURIComponent(string);
}
catch (e) {
result = unescape(string);
}
例如,ISO Latin编码的变音符号'ä'%E4
会在Firefox中引发异常,但UTF8编码的'ä'%C3%A4
则不会。
答案 1 :(得分:10)
我意识到这是一个老问题,但我不知道更好的解决方案。所以我这样做(感谢上面RobertPitt的评论):
function isEncoded(str) {
return typeof str == "string" && decodeURIComponent(str) !== str;
}
我还没有遇到过失败的情况。这并不意味着案件不存在。也许有人可以对此有所了解。
答案 2 :(得分:6)
鼓励您的客户使用encodeURIComponent()。请参阅此页面以获取解释:Comparing escape(), encodeURI(), and encodeURIComponent()。如果你真的想要确切地弄清楚某些东西是如何编码的,你可以尝试寻找一些escape()和encodeURI()不编码的字符。
答案 3 :(得分:2)
感谢@mika提供了很好的答案。也许只是一个改进因为unescape函数被认为是弃用的:
declare function unescape(s: string): string;
decodeURItoString(str): string {
var resp = str;
try {
resp = decodeURI(str);
} catch (e) {
console.log('ERROR: Can not decodeURI string!');
if ( (unescape != null) && (unescape instanceof Function) ) {
resp = unescape(str);
}
}
return resp;
}
答案 4 :(得分:0)
您无需区分它们。 escape()是所谓的百分比编码,它只与某些字符编码方式的URI编码不同。例如,Space使用escape编码为%20,但使用URI编码编码为+。解码后,您总能获得相同的值。