Skip to content

Instantly share code, notes, and snippets.

@xorgy
Forked from CatTail/htmlentity.js
Last active January 13, 2017 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xorgy/0ae65c3fa2e7b631654edf8f4c80b5ea to your computer and use it in GitHub Desktop.
Save xorgy/0ae65c3fa2e7b631654edf8f4c80b5ea to your computer and use it in GitHub Desktop.
Javascript: encode(decode) html text into html entity
// encode(decode) html text into html entity
function decodeHtmlEntity(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
function encodeHtmlEntity(str) {
var buf = '';
for (var i = 0; i < str.length; i++) {
buf += '&#'+ str.charCodeAt(i) + ';';
}
return buf;
};
var entity = '&#20182;&#22920;&#30340;&#19996;&#35199;&#21560;';
var str = '他妈的东西吸';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true
// undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment