极湖

无不用其“极”

JavaScript: 取得字符串的字节数

, ,

代码:
//四舍五入
function _round(num, X) {
    X = X || 2;
    return Math.round(num*Math.pow(10, X))/Math.pow(10, X);
}

//取得字符串的字节数
function _byteLength(str){
    //方法一:正则
    if(!str) return 0;
    return str.replace(/[^\x00-\xFF]/g,'**').length;
    //方法二:循环
    /*
    var byteLen=0,len=str.length;
    for(var i=0; i<len; i++){
        if(str.charCodeAt(i)>255){
            byteLen += 2;
        } else {
            byteLen++;
        }
    }
    return byteLen;
    */
}

//测试
var str = "試験helloテストテスト";
var size = _byteLength(str);
alert(size + ' bytes');
alert(_round(size/1024) + ' Kb');

修复 Debian/Ubuntu/Mint 软件包依赖关系ExtJS: 深度查找树节点

Write a comment

You must be logged in to write a comment. If you're not a registered member, please sign up.

February 2012
S M T W T F S
January 2012March 2012
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29