Skip to content

Instantly share code, notes, and snippets.

@AGresvig
Created November 13, 2014 11:39
Show Gist options
  • Save AGresvig/3b9c57f8e012d50ff575 to your computer and use it in GitHub Desktop.
Save AGresvig/3b9c57f8e012d50ff575 to your computer and use it in GitHub Desktop.
Javascript <-> UTF-8 conversion tool
var JStoUTF8Converter = {
encode: function(input) {
var output = '';
for (var i = 0; i < input.length; i++) {
var j = '\b\t\n\v\f\r"\'\\'.indexOf(input.charAt(i));
if (j != -1) {
output += '\\' + 'btnvfr"\'\\'.substr(j, 1);
} else if (input.substr(i, 2) == '</') {
output += '<\\/';
i++;
} else {
if (input.charCodeAt(i) > 255) {
output += '\\u' + ('000' + input.charCodeAt(i).toString(16)).right(4);
} else {
output += '\\x' + ('0' + input.charCodeAt(i).toString(16)).right(2);
}
} else {
output += input.charAt(i);
}
}
return output;
},
decode: function(input) {
try {
return !/([^\\]'|\r|\n)/.test(input) ? eval("'" + input + "'") : false;
} catch (e) {
return false;
}
}
};
module.exports = JStoUTF8Converter;
@AGresvig
Copy link
Author

Converts HTML to a string that can be stored in a JSON document (and back).
Inspired by http://coderstoolbox.net/string/#!encoding=xml&action=encode&charset=us_ascii

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