Skip to content

Instantly share code, notes, and snippets.

@WickyNilliams
Forked from CatTail/htmlentity.js
Last active February 23, 2023 13:54
Show Gist options
  • Save WickyNilliams/4ba14b89fbf5b3bd4b01 to your computer and use it in GitHub Desktop.
Save WickyNilliams/4ba14b89fbf5b3bd4b01 to your computer and use it in GitHub Desktop.
const ENTITY_REGEX = /&#x([0-9A-F]+);/gi
function entityToChar(substr: string, match: string) {
return String.fromCharCode(parseInt(match, 16))
}
export const HtmlEntity = {
decode: function (str: string) {
return str.replace(ENTITY_REGEX, entityToChar)
},
encode: function (str: string) {
let buf = ''
for (let i = 0; i < str.length; i++) {
buf += `&#x${str.charCodeAt(i).toString(16)};`
}
return buf
},
}
var entity = '&#x9ad8;&#x7ea7;&#x7a0b;&#x5e8f;&#x8bbe;&#x8ba1;';
var str = '高级程序设计';
console.assert(HtmlEntity.decode(entity) === str);
console.assert(HtmlEntity.encode(str) === entity);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment