Created
May 18, 2012 09:36
-
-
Save lsauer/2724281 to your computer and use it in GitHub Desktop.
JavaScript / Coffeescript : Lightweight Conversion of HTML Entities to ASCII / ASCII 2 HTML
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
html2ascii = (asciis) -> | |
asciis.map (e, i, a) -> | |
String.fromCharCode HTML_ENTITIES.indexOf(e) if -1 isnt HTML_ENTITIES.indexOf(e) | |
ascii2html = (asciis) -> | |
asciis.map (e, i, a) -> | |
String.fromCharCode +e if HTML_ENTITIES.hasOwnProperty(e) | |
HTML_ENTITIES = Array(255) | |
HTML_ENTITIES["34"] = """ | |
HTML_ENTITIES["38"] = "&" | |
HTML_ENTITIES["39"] = "'" | |
HTML_ENTITIES["60"] = "<" | |
HTML_ENTITIES["62"] = ">" | |
" ,¡¢,£,¤,¥,¦,§,¨,©,ª,«,¬,­,®,¯,°,±,²,³,´,µ,¶,·,¸,¹,º,»,¼,½,¾,¿,À,Á,Â,Ã,Ä,Å,Æ,Ç,È,É,Ê,Ë,Ì,Í,Î,Ï,Ð,Ñ,Ò,Ó,Ô,Õ,Ö,×,Ø,Ù,Ú,Û,Ü,Ý,Þ,ß,à,á,â,ã,ä,å,æ,ç,è,é,ê,ë,ì,í,î,ï,ð,ñ,ò,ó,ô,õ,ö,÷,ø,ù,ú,û,ü,ý,þ,ÿ".split(",").map (e, i, a) -> | |
HTML_ENTITIES[160 + i] = e | |
ascii2html [ 160, 165, 170 ] | |
html2ascii [ "£", "÷" ] |
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
//lsauer.com - lorenz lo sauer 2012 | |
//description: quick conversion from ASCII to HTML-ENTITIES and back in javascript | |
//entities start at ASCII 160 to 255, and are of the form ^&[#]?[a-zA-Z]{3,20};$ | |
var HTML_ENTITIES = Array(255); | |
HTML_ENTITIES['34'] = '"'; | |
HTML_ENTITIES['38'] = '&'; | |
HTML_ENTITIES['39'] = '''; | |
HTML_ENTITIES['60'] = '<'; | |
HTML_ENTITIES['62'] = '>'; | |
//concat and push.apply won't work for some reason? | |
' ,¡¢,£,¤,¥,¦,§,¨,©,ª,«,¬,­,®,¯,°,±,²,³,\ | |
´,µ,¶,·,¸,¹,º,»,¼,½,¾,¿,À,Á,Â,Ã,Ä,Å,Æ,Ç,\ | |
È,É,Ê,Ë,Ì,Í,Î,Ï,Ð,Ñ,Ò,Ó,Ô,Õ,Ö,×,Ø,Ù,Ú,Û,\ | |
Ü,Ý,Þ,ß,à,á,â,ã,ä,å,æ,ç,è,é,ê,ë,ì,í,î,ï,\ | |
ð,ñ,ò,ó,ô,õ,ö,÷,ø,ù,ú,û,ü,ý,þ,ÿ' | |
.split(',').map( function(e,i,a){ HTML_ENTITIES[160+i] = e;} ) | |
//e.g. convert from ASCII to | |
//pass an array of ascii numbers -> ascii integers to html symbols | |
function html2ascii(asciis){ | |
return asciis.map( function(e,i,a){ if (-1 !== HTML_ENTITIES.indexOf(e) ) return String.fromCharCode(HTML_ENTITIES.indexOf(e))} ) | |
} | |
function ascii2html(asciis){ | |
return asciis.map( function(e,i,a){ if (HTML_ENTITIES.hasOwnProperty(e)) return String.fromCharCode(+e)} ) | |
} | |
//example #1 | |
ascii2html([160,165,170]) | |
//>[" ", "¥", "ª"] | |
//example #2 | |
html2ascii(['£','÷']) | |
//>["¢", "ö"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment