JS方法 - 字符串處理函數封裝匯總 (更新中...)
阿新 • • 發佈:2018-10-21
byte 計算 class 等於 text mat return color gets
一、計算一段字符串的字節長度
字符串的charCodeAt()方法, 可返回字符串固定位置的字符的Unicode編碼,這個返回值是0-65535之間的整數,如果值<=255時為英文,反之為中文。 而,中文的字節長度為2,英文的字節長度為1。 依照這個規律封裝如下: 1 function getStrBytes(str){
2 str = str.toString();
3 var strLen = 0;
4 for (let s = 0; s < str.length; s++) {
5 if(str.charCodeAt(s) >= 255){
6 // 中文,字節為2.
7 strLen += 2;
8 }else{
9 // 非中文,字節為1.
10 strLen += 1;
11 }
12 }
13 return strLen;
14 }
簡化寫法:(思路是,初始化時,默認就把字符串的長度等於字節長度。遇到中文的時候,字節長度+1)
1 function getStrBytes(str){
2 str = str.toString();
3 var strLen,
4 count;
5 strLen = count= str.length;
6 for (let s = 0; s < strLen; s++) {
7 if(str.charCodeAt(s) >= 255)
8 count ++;
9 }
10 return count;
11 }
調用方法:
getStrBytes("gjf32425");
二、計算輸入文本框的字符個數
這個功能很常見,在評論區內一般會限制輸入文字個數,
多用於textarea右下角的數字提示器功能,提示用戶輸入的文字個數。
利用上邊計算出的字符串的字節,除以2取整就可以粗略當做用戶的字符個數。
1 function getStrNum(str){
2 return Math.ceil(getStrBytes(str)/2);
3 }
調用:
getStrNum("繼續努力加油!!耶!");
JS方法 - 字符串處理函數封裝匯總 (更新中...)