GetByteLength:prototype 示例

作者:chilleen 来源:ITPOW(原创) 日期:2007-3-20

JS 中的 String 对象具有 length 属性,但 length 只计算字符串长度,不计算以字节为单位的长度。

如果将一个英文字符插入数据库 char、varchar、text 类型的字段时占用一个字节,而一个中文字符插入时占用两个字节,为了避免插入溢出,就需要事先判断字符串的字节长度,要实现此功能,可利用下面的函数。

//以字节为单位返回字符串长度
//Unicode 编码小于等于 255 的,字节长度为 1;
//Unicode 编码大于 255 的,字节长度为 2。
String.prototype.GetByteLength = function ()
{
    //假设字符串每个字符的 Unicode 编码均小于等于 255,byteLength 为字符串长度;
    //再遍历字符串,遇到 Unicode 编码大于 255 时,为 byteLength 补加 1。
    var byteLength = this.length;
    var i = 0;
    for (i=0; i<this.length; i++)
    {
        if (this.charCodeAt(i) > 255)
        {
            byteLength++;
        }
    }
   
    return byteLength;
}
var str = "中国China";
document.write("<p>字符串长度:" + str.length + "</p>");
document.write("<p>字符串字节长度:" + str.GetByteLength() + "</p>");

相关阅读:

相关文章