Last active
August 4, 2016 16:39
-
-
Save nathanallen/c0bad7cecc8f7dbf97a08a797bcfb5ff to your computer and use it in GitHub Desktop.
Javascript Character Codes & Encodings [Script]
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
// Script to generate list of character codes, characters, and their respective URI/HTML encodings. | |
/* | |
* HTML Escape Utility Function | |
* Adapted from underscore library's _.escape method. | |
* source: http://underscorejs.org/#escape | |
*/ | |
var escape = (function() { | |
var ESCAPE_MAP = { | |
'&': '&', | |
'<': '<', | |
'>': '>', | |
'"': '"', | |
"'": ''', | |
'`': '`' | |
}; | |
var escaper = function(match) { | |
return ESCAPE_MAP[match]; | |
}; | |
var source = '(?:' + Object.keys(ESCAPE_MAP).join('|') + ')'; | |
var testRegexp = RegExp(source); | |
var replaceRegexp = RegExp(source, 'g'); | |
return function(string) { | |
string = string == null ? '' : '' + string; | |
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; | |
}; | |
}()); | |
/* | |
* For character codes n..0, outputs: | |
* charCode, char, url_encoding, html_encoding | |
*/ | |
function generateEncodings(n){ | |
var out = []; | |
while(n--){ | |
var char = String.fromCharCode(n); | |
out.push({ | |
charCode: n, | |
char: char, | |
uri_encoded: encodeURI(char), | |
html_escaped: escape(char) | |
// , html_encoded: "&#" + n + ";" // ? | |
}); | |
} | |
return out; | |
} | |
/* | |
* Driver Code | |
*/ | |
var result = generateEncodings(127); // first 127 characters | |
// console.table && console.table(result); // tabular format (Chrome Browser) | |
console.log(JSON.stringify(result, true, 4)); // JSON format |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment