javascript統計計算中文字串長度

來源:互聯網
上載者:User

如何讓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;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.