When changing to TypeScript I’m not allowed to use escape(string) anymore because it’s deprecated. The reason I still use it is that the alternatives encodeURI and encodeURIComponent give a different results.
JavaScript
x
4
1
var s = "Å"
2
console.log(escape(s));
3
console.log(encodeURI(s));
4
console.log(encodeURIComponent(s));
I don’t use this for URLs, but for a CSV export.
What are other alternatives that will give me the same result as escape(string)
?
Advertisement
Answer
In EcmaScript spec there is algorithm:
- Call ToString(string).
- Compute the number of characters in Result(1).
- Let R be the empty string.
- Let k be 0.
- If k equals Result(2), return R.
- Get the character at position k within Result(1).
- If Result(6) is one of the 69 nonblank ASCII characters ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 @*_+-./, go to step 14.
- Compute the 16-bit unsigned integer that is the Unicode character encoding of Result(6).
- If Result(8), is less than 256, go to step 12.
- Let S be a string containing six characters “%uwxyz” where wxyz are four hexadecimal digits encoding the value of Result(8).
- Go to step 15.
- Let S be a string containing three characters “%xy” where xy are two hexadecimal digits encoding the value of Result(8).
- Go to step 15.
- Let S be a string containing the single character Result(6).
- Let R be a new string value computed by concatenating the previous value of R and S.
- Increase k by 1.
- Go to step 5.
which can be coded like this:
JavaScript
1
25
25
1
(function(global) {
2
var allowed = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@*_+-./,';
3
global.escapeString = function(str) {
4
str = str.toString();
5
var len = str.length, R = '', k = 0, S, chr, ord;
6
while(k < len) {
7
chr = str[k];
8
if (allowed.indexOf(chr) != -1) {
9
S = chr;
10
} else {
11
ord = str.charCodeAt(k);
12
if (ord < 256) {
13
S = '%' + ("00" + ord.toString(16)).toUpperCase().slice(-2);
14
} else {
15
S = '%u' + ("0000" + ord.toString(16)).toUpperCase().slice(-4);
16
}
17
}
18
R += S;
19
k++;
20
}
21
return R;
22
};
23
24
})(typeof window == 'undefined' ? global : window);
25