Skip to content

Instantly share code, notes, and snippets.

@think49
Created February 1, 2011 04:50
Show Gist options
  • Save think49/805428 to your computer and use it in GitHub Desktop.
Save think49/805428 to your computer and use it in GitHub Desktop.
percentEncode.js : RFC3986 規定のパーセントエンコーディング
/**
* percentEncode.js
*
* @version 0.9.2
* @author think49
* @url https://gist.github.com/805428
*/
var percentEncode = (function () {
// decimal number to hex number
function decimalToHex (number) {
var positiveNumber, result, map, tmp, floor;
number = +number;
if (isNaN(number)) {
return number;
}
floor = Math.floor;
positiveNumber = number < 0 ? -1 : 1;
number *= positiveNumber;
map = {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'};
result = [];
do {
tmp = number % 16;
result.unshift(map.hasOwnProperty(tmp) ? map[tmp]: tmp);
number = floor(number / 16);
} while (number > 0);
result = result.join('');
return positiveNumber ? result : '-' + result;
}
// Percent-Encoding (RFC3986-2.1 Percent-Encoding)
function percentEncode (string) {
var fromCharCode = String.fromCharCode;
// If target character is not a "Unreserved Character", Percent-Encode the target character. (RFC3986-2.3: http://www.studyinghttp.net/rfc_ja/rfc3986#Sec2.3 )
return (string + '').replace(/[^a-zA-Z\d-._~]/g, function (token) {
var hex, result, reg, match, error;
hex = decimalToHex(token.charCodeAt(0));
if (typeof hex !== 'string') {
throw new TypeError(hex + ' is not a String');
}
if (hex.length % 2 !== 0) {
hex = '0' + hex;
}
if (!/^(?:[\da-fA-F]{2})+$/.test(hex)) {
throw new Error('not well-formed hex characters\r\n"' + hex + '"');
}
reg = /[\da-fA-F]{2}/g;
result = [];
do {
match = reg.exec(hex);
if (match) {
result.push('%' + match[0]);
}
} while (match);
/*
console.log(hex);
console.log(result);
*/
if (hex.length / 2 !== result.length) {
throw new Error('not well-formed Percent-Encoding Characters\r\n[' + result.join(', ') + ']');
}
return result.join('');
});
}
return percentEncode;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment