//判断当前字符是单字节还是双字节
1、判断当前字符编码大于255
String.prototype.lengthB = function(){
var b = 0;
var l = this.length;
if(l){
for (var i = 0; i < l; i++) {
if(this.charCodeAt(i)>255){
console.log("双字节");
b+=2;
}else{
console.log("单字节");
b++;
}
};
return b;
}else{
return 0;
}
}
var s = "我";
console.log(s.lengthB()); //2
2、如果字符转义序列大于4位,则说明是双字节
String.prototype.lengthB = function(){
var b = 0;
var l = this.length;
if(l){
for (var i = 0; i < l; i++) {
var c = this.charAt(i);
if(escape(c).length>4){
b+=2;
}else if(c != "\r"){
b++;
}
};
return b;
}else{
return 0;
}
}
var s = "123";
console.log(s.lengthB()); //3
3、使用正则表达式,匹配单字节字符
String.prototype.lengthB = function(){
var b = 0;
var l = this.length;
if(l){
for (var i = 0; i < l; i++) {
var c = this.charAt(i);
if(/^[\u0000 - \u00ff]$/.test(c)){
b++;
}else{
b+=2;
}
};
return b;
}else{
return 0;
}
}
var s = "我我";
console.log(s.lengthB()); //4
应用
/*************************************************************************
* DESC:主要是用来判断当前输入的字节数,以便做到限制输入标题的长度功能
**************************************************************************/
var matchWords;
function notifyTextLength() {
var inputNum = document.getElementById("txtTitle").value.replace(/[^\x00-\xff]/g, "**").length; //得到输入的字节数
if (inputNum <= 200) {
matchWords = document.getElementById("txtTitle").value.length;
document.getElementById("inputedWord").innerHTML = inputNum + "字节," + matchWords + "字符";
document.getElementById("inputtingWord").innerHTML = (200 - inputNum) + "字母,"+(Math.round(((200-inputNum)/2)-0.5))+"汉字";
}
if (inputNum > 200) {
document.getElementById("txtTitle").value = document.getElementById("txtTitle").value.substring(0, matchWords); //如果超过200字节,就截取到200字节
}
}