梦相随1006

版权归 梦相随1006 所有,未经 https://www.cnblogs.com/xin1006 作者许可,严禁转载

导航

JS字符串--中英文长度统计

   /**
         * 方式一   耗时间
         */
        function getStringLength(str){
           
            var sStr,iCount,i,strTemp ;
            iCount = 0 ;
            sStr = str.split("");//拆分出每一个字符
               for (i = 0 ; i < sStr.length ; i ++){
                 strTemp = escape(sStr[i]); //编码
                 if (strTemp.indexOf("%u",0) == -1){
                      iCount += 1 ;
                 }else{
                      iCount += 2 ;
                 }
             }
 
             return iCount ;
    }
    /**
     * 方式二
     */
        function   getLen1( str) {
               var totallength=0;  
               for (var i=0;i<str.length;i++){
                    var intCode=str.charCodeAt(i);
                    if (intCode>=0&&intCode<=128) {
                     totallength=totallength+1; //非中文单个字符长度加 1
                 }else{
                      totallength=totallength+2; //中文字符长度则加 2
                    }
               } 
         return totallength;
    }
    
    /**
     * 方式三 效率最高了
     */
        function   getLen2( str) {

    //将中文替换成两个英文字符来统计
               return str.replace(/[^\x00-\xff]/g,"aa").length;
    }

posted on 2013-03-15 15:05  梦相随1006  阅读(495)  评论(0编辑  收藏  举报