javascript 判斷中文字符長度的函數代碼
2024-05-06 14:21:20
供稿:網友
JS的字符串都是string對象,可以用string對象的length屬性可以獲取其長度,但是無論是中文、全角符號以及英文最小長度單位都是1,這與php的strlen()并不相同。
代碼如下:
function strlen(str) {
var s = 0;
for(var i = 0; i < str.length; i++) {
if(str.charAt(i).match(/[u0391-uFFE5]/)) {
s += 2;
} else {
s++;
}
}
return s;
}
抓取出每個字符,匹配全角字符和漢字的,則計2個字符,其他的則計1個字符。
代碼如下:
<script>
alert (fucCheckLength("中國a"));
function fucCheckLength(strTemp)
{
var i,sum;
sum=0;
for(i=0;i<strTemp.length;i++)
{
if ((strTemp.charCodeAt(i)>=0) && (strTemp.charCodeAt(i)<=255))
sum=sum+1;
else
sum=sum+2;
}
return sum;
}
</script>
會得到結果是:5 要得到的字節長度吧?請注意字節和字符的差異。而字節長度是和編碼有關系的,比如"中國a",gbk/gb2312編碼是5個字節,可是如果是utf-8,則是7個字節(utf-8下通常一個漢字3個字節)。
我們可以把所有字符轉換在gbk再操作,實例
代碼如下:
function Utf8ToUnicode(strUtf8)
{
var bstr = "";
var nTotalChars = strUtf8.length; // total chars to be processed.
var nOffset = 0; // processing point on strUtf8
var nRemainingBytes = nTotalChars; // how many bytes left to be converted
var nOutputPosition = 0;
var iCode, iCode1, iCode2; // the value of the unicode.
while (nOffset < nTotalChars)
{
iCode = strUtf8.charCodeAt(nOffset);
if ((iCode & 0x80) == 0) // 1 byte.
{
if ( nRemainingBytes < 1 ) // not enough data
break;
bstr += String.fromCharCode(iCode & 0x7F);
nOffset ++;
nRemainingBytes -= 1;
}
else if ((iCode & 0xE0) == 0xC0) // 2 bytes
{
iCode1 = strUtf8.charCodeAt(nOffset + 1);
if ( nRemainingBytes < 2 || // not enough data
(iCode1 & 0xC0) != 0x80 ) // invalid pattern
{
break;
}
bstr += String.fromCharCode(((iCode & 0x3F) << 6) | ( iCode1 & 0x3F));
nOffset += 2;
nRemainingBytes -= 2;
}
else if ((iCode & 0xF0) == 0xE0) // 3 bytes
{
iCode1 = strUtf8.charCodeAt(nOffset + 1);
iCode2 = strUtf8.charCodeAt(nOffset + 2);
if ( nRemainingBytes < 3 || // not enough data
(iCode1 & 0xC0) != 0x80 || // invalid pattern
(iCode2 & 0xC0) != 0x80 )
{
break;
}
bstr += String.fromCharCode(((iCode & 0x0F) << 12) |
((iCode1 & 0x3F) << 6) |
(iCode2 & 0x3F));
nOffset += 3;
nRemainingBytes -= 3;
}
else // 4 or more bytes -- unsupported
break;
}
if (nRemainingBytes != 0)
{
// bad UTF8 string.
return "";
}
return bstr;
}
如何解決這個問題.本文介紹使用js來獲取中文字長度方法
首先,我們定義一個新的函數getBytes()取得字符串的字節數,在javascript里,這個函數是標準函數。