Skip to content

Instantly share code, notes, and snippets.

@cosmomathieu
Forked from CatTail/htmlentity.js
Created December 19, 2017 16:38
Show Gist options
  • Save cosmomathieu/ee4d055d7607893d744d8a3801dacbf1 to your computer and use it in GitHub Desktop.
Save cosmomathieu/ee4d055d7607893d744d8a3801dacbf1 to your computer and use it in GitHub Desktop.
Javascript: encode(decode) html text into html entity
// encode(decode) html text into html entity
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
var entity = '高级程序设计';
var str = '高级程序设计';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment