字符串的字节数

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/iteye_13538/article/details/82075593
<script type="text/javascript">
<!--
/**字符编码数值对应的存储长度:    
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 (charCode <= 0x07ff) {   
            totalLength += 2;   
        } else if (charCode <= 0xffff) {   
            totalLength += 3; 
        } else{
			totalLength += 4; 
		}        
	}
	return totalLength; 
}
var str="my字符串образования";
alert("字符数"+str.length+" ,字节数"+str.getBytesLength());  
//Java中的字节数==="字符串".getBytes("UTF-8").length 
  //-->
</script>

 

 

展开阅读全文

没有更多推荐了,返回首页