Created
September 13, 2011 14:58
-
-
Save jarrodbell/1214016 to your computer and use it in GitHub Desktop.
URL Encode and Decode in JavaScript
This file contains hidden or 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
| /** | |
| * rfc3986 compatable encode of a string | |
| * | |
| * @param {String} string | |
| */ | |
| self.urlEncode = function (string) { | |
| function hex(code) { | |
| var hex = code.toString(16).toUpperCase(); | |
| if (hex.length < 2) { | |
| hex = 0 + hex; | |
| } | |
| return '%' + hex; | |
| } | |
| if (!string) { | |
| return ''; | |
| } | |
| string = string + ''; | |
| var reserved_chars = /[ \r\n!*"'();:@&=+$,\/?%#\[\]<>{}|`^\\\u0080-\uffff]/, | |
| str_len = string.length, i, string_arr = string.split(''), c; | |
| for (i = 0; i < str_len; i++) { | |
| if (c = string_arr[i].match(reserved_chars)) { | |
| c = c[0].charCodeAt(0); | |
| if (c < 128) { | |
| string_arr[i] = hex(c); | |
| } else if (c < 2048) { | |
| string_arr[i] = hex(192+(c>>6)) + hex(128+(c&63)); | |
| } else if (c < 65536) { | |
| string_arr[i] = hex(224+(c>>12)) + hex(128+((c>>6)&63)) + hex(128+(c&63)); | |
| } else if (c < 2097152) { | |
| string_arr[i] = hex(240+(c>>18)) + hex(128+((c>>12)&63)) + hex(128+((c>>6)&63)) + hex(128+(c&63)); | |
| } | |
| } | |
| } | |
| return string_arr.join(''); | |
| }; | |
| /** | |
| * rfc3986 compatable decode of a string | |
| * | |
| * @param {String} string | |
| */ | |
| self.urlDecode = function (string){ | |
| if (!string) { | |
| return ''; | |
| } | |
| return string.replace(/%[a-fA-F0-9]{2}/ig, function (match) { | |
| return String.fromCharCode(parseInt(match.replace('%', ''), 16)); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why not use Javascript's
encodeURIComponent()anddecodeURIComponent()functions for URL encoding and decoding? Are they not rfc3986 compatible?