获得字符串中文长度
2014-07-01 15:17:15 访问(1714) 赞(0) 踩(0)
// 获得字符串字数方法
function GetStrLength(strTemp) {
if (strTemp == null || strTemp == "")
return 0;
var i = 0;
var sum = 0;
var iLen = strTemp.length;
sum = 0;
for (i = 0; i < iLen; i++) {
if ((strTemp.charCodeAt(i) >= 0) && (strTemp.charCodeAt(i) <= 255))
sum = sum + 1;
else
sum = sum + 2;
}
return sum;
}
示例
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
获得字符串中文长度__慢子助手编程交流与共享网</title>
<link href="favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="Description" content="获得字符串中文长度" />
<meta name="Keywords" content="获得字符串中文长度" /></head>
<body>
<h1>获得字符串中文长度</h1>
输入:
<input type="text" value="慢子·助手" id="txt_Input" name="txt_Input" /><br />
输出:
<input type="text" id="txt_Output" name="txt_Output" /><br />
<input type="button" value="测试" onclick="onGetResult();" />
</body>
</html>
<script language="javascript" type="text/javascript">
// 获得字符串字数方法
function GetStrLength(strTemp) {
if (strTemp == null || strTemp == "")
return 0;
var i = 0;
var sum = 0;
var iLen = strTemp.length;
sum = 0;
for (i = 0; i < iLen; i++) {
if ((strTemp.charCodeAt(i) >= 0) && (strTemp.charCodeAt(i) <= 255))
sum = sum + 1;
else
sum = sum + 2;
}
return sum;
}
function onGetResult() {
var theInput = document.getElementById("txt_Input").value;
var theResult = GetStrLength(theInput) + "";
document.getElementById("txt_Output").value = theResult;
}
</script>
运行代码
上一条:
下一条:
相关评论
发表评论