如何讓JS統計的字串長度與php一致呢?這裡的函數代碼只是針對GBK下編碼的字元,一個漢字等於二個字元。代碼如下:
| 代碼如下 |
複製代碼 |
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; } |