Last active
May 9, 2017 08:36
-
-
Save kyrene-chew/56a8b491ab5799c9cc80693e268394bb to your computer and use it in GitHub Desktop.
JavaScript - Handles encoding and decoding of HTML entities
This file contains hidden or 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
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