JS计算字符串长度(中文算2个)

       /**
         * @return {number}
         */
        getRealLength = function(str) {
            var realLength = 0, len = str.length, charCode = -1;
            for (var i = 0; i < len; i++) {
                charCode = str.charCodeAt(i);
                if (charCode >= 0 && charCode <= 128) realLength += 1;
                else realLength += 2;
            }
            return realLength;
        };    

使用:alert(getRealLength("中国上海123"));

posted @ 2013-11-14 09:40  Duelsol  阅读(463)  评论(0编辑  收藏  举报