Skip to content

Instantly share code, notes, and snippets.

@rawroland
Forked from WickyNilliams/htmlentity.ts
Created May 12, 2017 09:02
Show Gist options
  • Save rawroland/175e7bc93cf63b3f8050ba1c312ffd9f to your computer and use it in GitHub Desktop.
Save rawroland/175e7bc93cf63b3f8050ba1c312ffd9f to your computer and use it in GitHub Desktop.
// encode(decode) html text into html entity (assuming entity is hex)
var HtmlEntity = {
decode : function(str) {
return str.replace(/&#x([0-9A-F]+);/gi, function(match, dec) {
return String.fromCharCode(parseInt(dec, 16));
});
},
encode : function(str) {
var buf = [];
for (var i = 0, length = str.length; i < length; i++) {
buf.push("&#x" + str[i].charCodeAt().toString(16) + ";");
}
return buf.join("");
}
};
var entity = '&#x9ad8;&#x7ea7;&#x7a0b;&#x5e8f;&#x8bbe;&#x8ba1;';
var str = '高级程序设计';
console.log(HtmlEntity.decode(entity) === str); // true
console.log(HtmlEntity.encode(str) === entity); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment