统计字符串长度

来源:互联网 发布:上海仙谷网络新三板 编辑:程序博客网 时间:2024/06/05 10:06

javascript获得字符串可以用length

        var strE="hello";        var strC="我们哈获得";        document.write("strE='hello'的长度:"+strE.length+"<br/>"); //5        document.write("strC='hello'的长度:"+strC.length); // 5
一个英文字母占一个字节,所以length=字节数

一个中文占两个字节,length != 字节数

        var strE="hello";  //5        var strC="我们哈获得"; //10        var bytesCount=0;        for(var i=0; i<strC.length;i++){            if(/^[\u0000-\u00ff$]/.test(strC)){                bytesCount +=1;            }else {                bytesCount +=2;            }        }        alert(bytesCount); 

匹配中文字符的正则表达式: [\u4e00-\u9fa5]

匹配双字节字符(包括汉字在内):[^\x00-\xff]

charAt(num) //获取字符串的num位置的字符串

charCodeAt(num) //获取字符串的num未知的字符串的unicode编码

fromCharCode(num) //获取unicode编码对应的字符串

0 0