js獲取字符串的字節長度

//字符編碼數值對應的存儲長度:     
//UCS-2編碼(16進制) UTF-8 字節流(二進制)    
//0000 - 007F       0xxxxxxx (1字節)     
//0080 - 07FF       110xxxxx 10xxxxxx (2字節)     
//0800 - FFFF       1110xxxx 10xxxxxx 10xxxxxx (3字節)    
String.prototype.getBytesLength = function() {   
    var totalLength = 0;     
    var charCode;  
    for (var i = 0; i < this.length; i++) {  
        charCode = this.charCodeAt(i);  
        if (charCode < 0x007f)  {     
            totalLength++;     
        } else if ((0x0080 <= charCode) && (charCode <= 0x07ff))  {     
            totalLength += 2;     
        } else if ((0x0800 <= charCode) && (charCode <= 0xffff))  {     
            totalLength += 3;   
        } else{  
            totalLength += 4;   
        }          
    }  
    return totalLength;   
}  
var str="你好嗎?111?";  
alert("字符數"+str.length+" ,字節數"+str.getBytesLength());    
//Java中的字節數==="字符串".getBytes("UTF-8").length   
  //-->

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章