序言
程序前臺(tái)頁面中,經(jīng)常有一些有輸入長度限制的input和textarea,限制長度的方法有標(biāo)簽上加入maxlength屬性和使用js的length屬性獲取輸入的內(nèi)容長度。
以上的方法適用于大多數(shù)情況,但需求更復(fù)雜一些,比如輸入框中最多輸入10個(gè)全角文字或20個(gè)半角文字,即只能輸入10個(gè)漢字或者20個(gè)英文數(shù)字。這時(shí)length屬性就變得不適用。
解決方法
將輸入的字符轉(zhuǎn)為Unicode編碼,根據(jù)編碼來判斷哪些是全角字符(對應(yīng)length+=2),哪些是半角字符(對應(yīng)length+=1)。
js版本
/**
* 全角文字的長度
* @param 輸入文字
* @return 文字長度
*/
function getMojiLength(str) {
var realLength = 0;
var len = str.length;
var charCode = -1;
for ( var i = 0; i < len; i++) {
charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 254) {
// 0-255中的全角文字,依次對應(yīng)下面的字符
// ¢ , £ , § , ¨ , ? , ? , ˉ , ° , ± , ′ , μ , ? , · , ? , ? , × , ÷
if (charCode == 162
|| charCode == 163
|| charCode == 167
|| charCode == 168
|| charCode == 171
|| charCode == 172
|| charCode == 175
|| charCode == 176
|| charCode == 177
|| charCode == 180
|| charCode == 181
|| charCode == 182
|| charCode == 183
|| charCode == 184
|| charCode == 187
|| charCode == 215
|| charCode == 247) {
realLength += 2;
} else {
realLength += 1;
}
} else if (charCode >= 65377 && charCode <= 65439) {
if (charCode == 65381) { // '?'該字符的長度為兩個(gè)字節(jié)
realLength += 2;
} else {
realLength += 1;
}
} else {
realLength += 2;
}
}
return realLength;
}
Java版本
/**
* 取得文字的長度
* @param moji 輸入文字
* @return 長度
*/
public static int getMojiLength(String moji) {
if (isEmpty(moji)) {
return 0;
}
char charCode;
int mojiLen = 0;
for (int i = 0; i < moji.length(); i++) {
charCode = moji.charAt(i);
if (charCode >= 0 && charCode <= 254) {
// 0-255中的全角文字
if (charCode == 162
|| charCode == 163
|| charCode == 167
|| charCode == 168
|| charCode == 171
|| charCode == 172
|| charCode == 175
|| charCode == 176
|| charCode == 177
|| charCode == 180
|| charCode == 181
|| charCode == 182
|| charCode == 183
|| charCode == 184
|| charCode == 187
|| charCode == 215
|| charCode == 247) {
mojiLen += 2;
} else {
mojiLen += 1;
}
} else if (charCode >= 65377 && charCode <= 65439) {
if (charCode == 65381) {
mojiLen += 2;
} else {
mojiLen += 1;
}
} else {
mojiLen += 2;
}
}
return mojiLen;
}
說明
以上的代碼思路是先將問字符轉(zhuǎn)為Unicode編碼,先判斷是否屬于0-255范圍內(nèi),除了幾個(gè)特殊的字符是兩個(gè)字節(jié),其他為一個(gè)字節(jié)。接著判斷65377-65439范圍內(nèi)的長度,65381(對應(yīng)‘?’字符,占兩個(gè)字節(jié)),其余是一個(gè)字節(jié),除此之外范圍內(nèi)的字符都是兩個(gè)字節(jié)。
補(bǔ)充
根據(jù)Unicode編碼獲取對應(yīng)漢字的方法,js為fromCharCode()
var char = "";
var codeArray = [162,163,167,168,171,172,175,176,177,180,181,182,183,184,187,215,247];
for(var i=0; i<codeArray.length; i++){
char += String.fromCharCode(codeArray[i]) + " , ";
}
//char = ¢ , £ , § , ¨ , ? , ? , ˉ , ° , ± , ′ , μ , ? , · , ? , ? , × , ÷
Java寫法更為簡單
int charCode = 162;
String charValue = "" + (char)charCode;
// charValue = ¢
以上介紹的方法還有其他用途,比如文本框中動(dòng)態(tài)追加內(nèi)容時(shí),要進(jìn)行合理的換行(兩段的內(nèi)容長度小于文本框長度,則顯示在同一行,若超出則換行顯示),因?yàn)闈h字占得位置比較字母數(shù)字大,不能根據(jù)文字長度來判斷,這時(shí)就可以計(jì)算文字的真實(shí)長度來判斷是否換行。