js獲取字符串的字節長度

    //得到輸入框中字符長度
    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)

輸出:4spa

相關文章
相關標籤/搜索