注意:基於 JS 中中文和英文、數字字符長度都是 1
//獲取字符串長度(中文占2個字符) owner.getBytesCount = function(str) { var bytesCount = 0; if (str != null) { for (var i = 0; i < str.length; i++) { var c = str.charAt(i); if (c.match(/[^\x00-\xff]/ig) != null) //全角 { bytesCount += 2; } else { bytesCount += 1; } } } return bytesCount; }
算法一(推薦好理解):
var str = "01abc23中文45中文67中a文89中文"; // str = str.replace(/[^\x00-\xff]/g, "$&\x01").replace(/.{10}\x01?/g, "$&\n").replace(/\x01/g, ""); // console.log(str) var iPageSize = 10; var strArray = []; var tempStr = ""; var iTotalLength = commUtils.getBytesCount(str); for (var i = 0; i < str.length; i++) { var iCount = commUtils.getBytesCount(str[i]); var iCountTemp = commUtils.getBytesCount(tempStr); //iCountTemp + iCount >= iPageSize 這里可能出現兩種情況: //長度等於 iPageSize 或 等於 iPageSize + 1(最后一個為中文字符就等於 9 + 2 情況) if (iCountTemp + iCount >= iPageSize) { tempStr += str[i]; strArray.push(tempStr); console.log("iCountTemp + iCount >= iPageSize " + tempStr) tempStr = ""; } else { tempStr += str[i]; } } // //最后一次尾巴 if (tempStr.length > 0) strArray.push(tempStr) for (var i = 0; i < strArray.length; i++) { console.log(strArray[i]) }
算法二:
var iIdx = 0; var resArray = []; var i = 0; while (commUtils.getBytesCount(str) > iPageSize) { var iCount = commUtils.getBytesCount(str[i]); // console.log('i = ' + i) if (iIdx + iCount > iPageSize) { // console.log('iIdx = ' + iIdx) // console.log(str.substring(0, i)) resArray.push(str.substring(0, i)) str = str.substring(i, str.length) console.log('str = ' + str) iIdx = 0; i = 0; } else { iIdx = iIdx + iCount; i++; } } // //最后一次尾巴 if (str.length > 0) resArray.push(str) // console.log(resArray.length) for (var i = 0; i < resArray.length; i++) { console.log(resArray[i]) }