Skip to content

Instantly share code, notes, and snippets.

@nathanallen
Last active August 4, 2016 16:39
Show Gist options
  • Save nathanallen/c0bad7cecc8f7dbf97a08a797bcfb5ff to your computer and use it in GitHub Desktop.
Save nathanallen/c0bad7cecc8f7dbf97a08a797bcfb5ff to your computer and use it in GitHub Desktop.
Javascript Character Codes & Encodings [Script]
// 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 = {
'&': '&',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;',
'`': '&#x60;'
};
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