Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

AGresvig commented Nov 13, 2014

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

Loading

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