您的位置:首页 > Web前端 > JavaScript

js判断字符串长度,中文占两个字符

2013-04-21 01:34 543 查看
分析前言:

// \x00-\xff 是字符编码的范围,如果查过这个范围,就不是字母和数字了,
//把全部符合\x00-\xff条件的字符用**替换,然后计算长度,即遇到一个中文就用**替换,计算为两位
var length = name.replace(/[^\x00-\xff]/g,"**").length;


方案1:

用js判断字符串的长度:

如:str=”中国”,alert(str.length),则提示长度为2。

做如下处理后:

str=str.replace(/[^\x00-\xff]/g, 'xx'),alert(str.length)则长度提示为4


方案2:

function strlen(str){
var len = 0;
for (var i=0; i<str.length; i++) {
  var c = str.charCodeAt(i);
  //单字节加1
  if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
  len++;
  } else {
   len+=2;
  }
}
return len;
}


sample:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JS-TRING</title>
<script type="text/javascript" >
//方案1
function wayOne(){
var str = document.getElementById('tt').value;
str=str.replace(/[^\x00-\xff]/g, 'xx');
alert(str.length);
}
//方案2-01
function wayTwo(){
var str = document.getElementById('tt').value;
alert(WidthCheck(str, 6));
}
//方案2-02
function WidthCheck(s, n){
var w = 0;
for (var i=0; i<s.length; i++) {
var c = s.charCodeAt(i);
//单字节加1
if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
w++;
} else {
w+=2;
}
}
if (w == n) {
return true;
}
return false;
}
</script>
</head>
<body>
<div style="margin:10px 0;">
<form>
<input type="text" id="tt" />
<input type="button" value="wayOne" onclick="wayOne();" />
<input type="button" value="wayTwo" onclick="wayTwo();" />
</form>
</div>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐