-
-
Save kachar/373b857dd842a219b4849eff71b9eca5 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 | |
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 |
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
const decodeHtmlEntity = function (str: string) { | |
return str.replace(/&#(\d+);/g, function (match: string, dec: number) { | |
return String.fromCharCode(dec) | |
}) | |
} | |
const encodeHtmlEntity = function (str: string) { | |
const buf = [] | |
for (let i = str.length - 1; i >= 0; i--) { | |
buf.unshift(['&#', str.charCodeAt(i), ';'].join('')) | |
} | |
return buf.join('') | |
} | |
const entity = '高级程序设计'; | |
const str = '高级程序设计'; | |
console.log(decodeHtmlEntity(entity) === str); | |
console.log(encodeHtmlEntity(str) === entity); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment