Skip to content

Instantly share code, notes, and snippets.

@kyrene-chew
Last active May 9, 2017 08:36
Show Gist options
  • Save kyrene-chew/56a8b491ab5799c9cc80693e268394bb to your computer and use it in GitHub Desktop.
Save kyrene-chew/56a8b491ab5799c9cc80693e268394bb to your computer and use it in GitHub Desktop.
JavaScript - Handles encoding and decoding of HTML entities
htmlEntities = {
// encode special characters to html encoded characters
encode: function (text) {
var encodedString = '';
for (i = 0; i < text.length; i++) {
if (text.charCodeAt(i) > 127) {
encodedString += '&#' + text.charCodeAt(i) + ';';
} else {
encodedString += text.charAt(i);
}
}
return encodedString;
},
// decode html encoded characters to original characters
decode: function (text) {
return text.replace(/&#(\d+);/g, function (match, dec) {
return String.fromCharCode(dec);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment