如果不考虑通用性,且html为UTF8编码的,可以用UTF8版本
utf8_strlen2是escape版,utf8_strlen是utf8专用版
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="../../jquery.min.js"></script>
<script type="text/javascript" src="../../jquery.easyui.min.js"></script>
<script type="text/javascript">
function testGetCharBytes() {
alert(utf8_strlen($("#username").val()));
}
function utf8_strlen2(str)
{
var cnt = 0;
for( i=0; i<str.length; i++)
{
var value = str.charCodeAt(i);
if( value < 0x080)
{
cnt += 1;
}
else if( value < 0x0800)
{
cnt += 2;
}
else
{
cnt += 3;
}
}
return cnt;
}
function utf8_strlen(str)
{
var str_encode = escape(str);
var cnt = 0;
for( i=0; i<str_encode.length; i++)
{
if( str_encode.charAt(i) == "%")
{
if( str_encode.charAt(i+1) == "u" )
{
var value = parseInt(str_encode.substr(i+2,4),16);
if( value < 0x0800)
{
cnt += 2;
}
else
{
cnt += 3;
}
i = i+5;
}
else
{
cnt++;
i = i+2;
}
}
else
{
cnt++;
}
}
return cnt;
}
</script>
</head>
<body>
<input type="text" name="username" id="username"></input><br/>
<input type="button" value="测试" onclick="testGetCharBytes();"></input>
</body>
</html>