Created
November 13, 2014 11:39
-
-
Save AGresvig/3b9c57f8e012d50ff575 to your computer and use it in GitHub Desktop.
Javascript <-> UTF-8 conversion tool
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
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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