拓展javascript内置函数

1、获取字符串字节数

//获取字符串字节数
//方法一
/* */
String.prototype.getBytesLength = function () {
    var length = 0;
    for (i = 0; i < this.length; i++) {
        iCode = this.charCodeAt(i);
        if ((iCode >= 0 && iCode <= 255) || (iCode >= 0xff61 && iCode <= 0xff9f)) {
            length += 1;
        } else {
            length += 2;
        }
    }
    return length;
}

//方法二
/* */
String.prototype.getBytesLength = function () {
    return this.replace(/[^\x00-\xff]/gi, "--").length;
}

document.write("Sn杨".getBytesLength());//结果:4

 

posted @ 2013-08-02 17:57  microsoftzhcn  阅读(243)  评论(0编辑  收藏  举报