[英]Alternatives to escape(string) in JavaScript
When changing to TypeScript I'm not allowed to use escape(string) anymore because it's deprecated . 当更改为TypeScript时,因为已弃用 ,所以不再允许使用escape(string)。 The reason I still use it is because the alternatives encodeURI and encodeURIComponent gives a different result. 我仍然使用它的原因是因为替代方法encodeURI和encodeURIComponent给出了不同的结果。
var s = "Å" alert(escape(s)); alert(encodeURI(s)) alert(encodeURIComponent(s))
I don't use this for URLs, but for a CSV export. 我不是将其用于URL,而是用于CSV导出。
Other alternatives that will give me the same result at escape(string) used to provide? 其他选择是否会给我提供与使用escape(string)相同的结果?
In EcmaScript spec there is algorithm: 在EcmaScript规范中,有以下算法:
which can be coded like this: 可以这样编码:
(function(global) {
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./,';
global.escapeString = function(str) {
str = str.toString();
var len = str.length, R = '', k = 0, S, chr, ord;
while(k < len) {
chr = str[k];
if (allowed.indexOf(chr) != -1) {
S = chr;
} else {
ord = str.charCodeAt(k);
if (ord < 256) {
S = '%' + ("00" + ord.toString(16)).toUpperCase().slice(-2);
} else {
S = '%u' + ("0000" + ord.toString(16)).toUpperCase().slice(-4);
}
}
R += S;
k++;
}
return R;
};
})(typeof window == 'undefined' ? global : window);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.