码迷,mamicode.com
首页 > Web开发 > 详细

JS计算字符串实际长度

时间:2014-11-17 13:43:47      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   for   div   

http://www.qttc.net/201207136.html

 

// UTF8字符集实际长度计算
function getStrLeng(str){
    var realLength = 0;
    var len = str.length;
    var charCode = -1;
    for(var i = 0; i < len; i++){
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) {
            realLength += 1;
        }else{
            // 如果是中文则长度加3
            realLength += 3;
        }
    }
    return realLength;
}

 

// GBK字符集实际长度计算
function getStrLeng(str){
    var realLength = 0;
    var len = str.length;
    var charCode = -1;
    for(var i = 0; i < len; i++){
        charCode = str.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128) {
            realLength += 1;
        }else{
            // 如果是中文则长度加2
            realLength += 2;
        }
    }
    return realLength;
}

 

JS计算字符串实际长度

标签:style   blog   http   io   color   ar   sp   for   div   

原文地址:http://www.cnblogs.com/wangjunwei/p/4103309.html

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