Created
February 17, 2017 06:45
-
-
Save zhoukekestar/cc3f633ca4af0d531964001f02aa64cc to your computer and use it in GitHub Desktop.
encodeURIComponent & decodeURIComponent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const s1 = '\\[ \\{ \\} \\] , / \\? : @ & = \\+ \\$ # " \\\\'.split(' '); // '[{}],/\?:@&=\+$#"\ ' | |
const s2 = '%5B%7B%7D%5D%2C%2F%3F%3A%40%26%3D%2B%24%23%22%5C%20'.match(/.{3}/g); // encodeURIComponent('[{,/\?:@&=\+$#"\\ ') | |
const s3 = '[{}],/\?:@&=\+$#"\\ '.split(''); | |
s1.push(' '); | |
module.exports.encodeURIComponent = function encodeURIComponent(str) { | |
let res = `${str}`; | |
for (let i = 0; i < s1.length; i += 1) { | |
res = res.replace(new RegExp(s1[i], 'g'), s2[i]); | |
} | |
return res; | |
}; | |
module.exports.decodeURIComponent = function decodeURIComponent(str) { | |
let res = `${str}`; | |
for (let i = 0; i < s1.length; i += 1) { | |
res = res.replace(new RegExp(s2[i], 'g'), s3[i]); | |
} | |
return res; | |
}; | |
/** | |
console.log(encodeURIComponent('http://www.abc.com/abc/abc.html?a=a')) | |
console.log(myencodeURIComponent('http://www.abc.com/abc/abc.html?a=a')) | |
console.log(encodeURIComponent('http://www.abc.com/abc/abc.html?a=a') === myencodeURIComponent('http://www.abc.com/abc/abc.html?a=a')) | |
console.log(encodeURIComponent('[{}],/\?:@&=\+$#"\\ ')) | |
console.log(myencodeURIComponent('[{}],/\?:@&=\+$#"\\ ')) | |
console.log(encodeURIComponent('[{}],/\?:@&=\+$#"\\ ') === myencodeURIComponent('[{}],/\?:@&=\+$#"\\ ')) | |
console.log(decodeURIComponent('%5B%7B%7D%5D%2C%2F%3F%3A%40%26%3D%2B%24%23%22%5C%20')) | |
console.log(mydecodeURIComponent('%5B%7B%7D%5D%2C%2F%3F%3A%40%26%3D%2B%24%23%22%5C%20')) | |
console.log(decodeURIComponent('%5B%7B%7D%5D%2C%2F%3F%3A%40%26%3D%2B%24%23%22%5C%20') === mydecodeURIComponent('%5B%7B%7D%5D%2C%2F%3F%3A%40%26%3D%2B%24%23%22%5C%20')) | |
console.log(decodeURIComponent('http%3A%2F%2Fwww.abc.com%2Fabc%2Fabc.html%3Fa%3Da')) | |
console.log(mydecodeURIComponent('http%3A%2F%2Fwww.abc.com%2Fabc%2Fabc.html%3Fa%3Da')) | |
console.log(decodeURIComponent('http%3A%2F%2Fwww.abc.com%2Fabc%2Fabc.html%3Fa%3Da') === mydecodeURIComponent('http%3A%2F%2Fwww.abc.com%2Fabc%2Fabc.html%3Fa%3Da')) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment