首页 > Web开发 > 详细

js获取字符串的字节长度

时间:2018-08-02 10:41:20      阅读:126      评论:0      收藏:0      [点我收藏+]
    //获得输入框中字符长度
    function getLength(val) {  
        var str = new String(val);  
        var bytesCount = 0;  
        for (var i = 0 ,n = str.length; i < n; i++) {  
            var c = str.charCodeAt(i);  
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {  
                bytesCount += 1;  
            } else {  
                bytesCount += 2;  
            }  
        }  
        return bytesCount;  
    }  
var str="你好"

getLength(str)

输出:4

 

js获取字符串的字节长度

原文:https://www.cnblogs.com/Web-Architecture/p/9405635.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!