Javascript判断日文全角半角长度

    今天遇到需要判断在输入框中输入全角与半角的文字个数,例如全角可以输入10个,而半角可以输入20个。在网上搜寻了下,有篇文章是关于Javascript,重点在于将字符串转换成unicode编码,而AS和Javascript有现成的charCodeAt()函数。

 

    并不是所有的0-255之间的Unicode都是1个字节长的!!而且,日文的假名有半角的形式(Unicode是65377-65439,其中 65381除外)!!,并不是只有这些是半角的,还有很多字符也是半角的!!所以说,仅仅靠判断是不是在0-255里面是不行的。

     考虑到Unicode包括了所有国家的各种字符,而且这些字符又是全角半角交杂的,所以,不会有一个完美的JS方法来进行半角字符的校验。但是因为一般别 的字符也用不上,以后做的多是对日项目,所以还是沿用0-255的方法,然后抠掉一些全角的,再加上对半角日文的校验,写成以下一个方法,供研究使用:

 

function calcUTFByte(str) { var len=0; for (var i=0;i<str.length;i++) { var temp = str.charCodeAt(i); if ( temp >= 0 && temp <= 254) { //以下是0-255之内为全角的字符 if ( temp == 162 || temp == 163 || temp == 167 || temp == 168 || temp == 171 || temp == 172 || temp == 175 || temp == 176 || temp == 177 || temp == 180 || temp == 181 || temp == 182 || temp == 183 || temp == 184 || temp == 187 || temp == 215 || temp == 247) { len+=2; } len++; } else if ( temp >= 65377 && temp <= 65439) { if ( temp == 65381 ) { len+=2; } len++; } else { len+=2; } }//for end return len; }

 

 

 

 

该文章转自:http://hi.baidu.com/txzw/blog/item/de3a25c7f6476ed6d000601e.html

你可能感兴趣的:(JavaScript,c,function)