原来一直以为javascript判断字符串长度,很简单的一件事情。只用通过.length就可以轻松搞定。直至最近
才发现自己一直在错。呵呵!
javascript判断字符串长度注意:
中文和英文字符。特殊的符号。加减乘除等!
其实判断字符长度,应该判断字节长度。
以前网上有中很流行的方法。
String.prototype.getBytesLength = function() {
return this.replace(/[^\x00-\xff]/g, "--").length;
};
但是该方法存在漏洞。比如 +、-(在中文模式下输入)就会判断出来长度是1.但是你存入到数据库中。
在数据库中这些字符长度却是占2.(本人只做了oracle的验证,其他的没测试过。)
咱认为比较合理的教验方法:
String.prototype.getBytesLength = function() {
var bytelen = 0;
var chars = this.split('');
for(i = 0; i<chars.length; i++)
{
var char = chars[i];
var urichar = encodeURI(char);
bytelen += urichar.length == 1 ? 1 : urichar.length / 3;
}
return bytelen;
};
Java中判断字符字节长度:
public static void main(String[] args)
{
String s="+";
String ss="×";
System.out.println("英文长度:"+s.getBytes().length);
System.out.println("中文长度:"+ss.getBytes().length);
}