Skip to content

Instantly share code, notes, and snippets.

@jarrodbell
Created September 13, 2011 14:58
Show Gist options
  • Select an option

  • Save jarrodbell/1214016 to your computer and use it in GitHub Desktop.

Select an option

Save jarrodbell/1214016 to your computer and use it in GitHub Desktop.
URL Encode and Decode in JavaScript
/**
* 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));
});
};
@callicoder
Copy link
Copy Markdown

Why not use Javascript's encodeURIComponent() and decodeURIComponent() functions for URL encoding and decoding? Are they not rfc3986 compatible?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment