~ overflow ~

Archive for October 18th, 2008

Javascript to Replace Accent Chars

by admin on Oct.18, 2008, under Coding

Problem:

convert accent html encoded chars, like ç , to their real values in javascript

Solution:


var _chr=[];var _etn=[];for(var x=0;x<95;x++){_chr[x]=(x+161);_etn[x]="&#"+(x+161)+";";} // replacing all chars could be slow you would like to restrict it to only the accent chars or the ones that you like
function chr(x){return String.fromCharCode(x);}
function e2c(s){for(var x=0;x<95;x++){var m=s.indexOf(_etn[x]);while(m!=-1){s=s.replace(_etn[x],chr(_chr[x]));m=s.indexOf(_etn[x]);}}return s;}

you can test by:

alert(e2c(“&#161;&#161;&#161;&#161;&#162;&#231;&#231;&#227;&#164;&#165;&#191;”));

to do the reverse just change the order of the replace vars

note that javascript is lame and don’t have array replace and it will only replace a single char on the string (even if there’s more) so lots of loops had to be added to it, this might be a drawback if you use this too many times into a same page or into very large texts.

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!