-
-
Save xorgy/0ae65c3fa2e7b631654edf8f4c80b5ea to your computer and use it in GitHub Desktop.
Javascript: encode(decode) html text into html entity
This file contains 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
// 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 = '他妈的东西吸'; | |
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