码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 计算字符串的字节长度

时间:2014-10-17 18:13:48      阅读:306      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   使用   java   for   sp   

  在做前端验证表单时,有时候要检测一个字符串的字节长度,保证其字节长度不超过数据库表中对应字段允许的最大长度。

  不废话,上方法

  1.我们通常遇到的情况都是中文+英文,所以可以判断每个字符的 Unicode 编码值,大于255,表示中文,字节应该比英文大1个字节:

1 function byteLength(str){
2     var byteLen = str.length, len = str.length, i;
3     for(i = 0;i<len;i++){
4         if(str.charCodeAt(i) > 255){
5             byteLen++;
6         }
7     }
8     return byteLen;
9 }

  要注意的是,中文字符对应的字节数可能会因使用的字符编码不同而不同。  

  2.解决不同编码,中文字符对应字节数不同的问题,主要是针对utf-16:

 1 //utf-8 是可变长度的 Unicode 编码格式,每个字符对应1~4个字节
 2 //utf-16大部分使用两个字节编码,编码超出65535(00ffff)的使用4个字节
 3 function byteLength(str, charset){
 4     var total = 0,
 5         charcode,
 6         i,
 7         len = str.length,
 8         byteLen,
 9         charset = charset ? charset.toLowerCase() : ‘‘;
10     if(charset === ‘utf16‘ || charset === ‘utf-16‘){
11         for(i = 0;i<len;i++){
12             if(str.charCodeAt(i) <= 0xffff){
13                 byteLen += 2;
14             }else{
15                 byteLen += 4;
16             }
17         }
18     }else{
19         for(i = 0;i<len;i++){
20             if(str.charCodeAt(i) <= 0x007f){
21                 byteLen += 1;
22             }else if(str.charCodeAt(i) <= 0x07ff){
23                 byteLen += 2;
24             }else if(str.charCodeAt(i) <= 0xffff){
25                 byteLen += 3;
26             }else{
27                 byteLen += 4;
28             }
29         }
30     }
31     return byteLen;
32 }

  参考《javascript框架设计》

javascript 计算字符串的字节长度

标签:style   blog   color   io   ar   使用   java   for   sp   

原文地址:http://www.cnblogs.com/MiCoo/p/4031616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!