前言
日常開發過程中,有些時候我們想使用textarea,然后限制輸入的長度,在textarea末尾顯示剩余可輸入的字節數。
如下圖:
解決方法:
常用的有三種方法:
1、通過判斷charCodeAt,區分字母與中文 ,然后計算字符串的長度。
2、通過使用charCodeAt 和 0xff00區分中文與英文,這個代碼量稍微減少一些。
3、使用正則,把輸入的中文,轉成英文。1個中文等於兩個英文,最后計算英文個數。
代碼如下:
方法一:
var obj = {};
obj.GetLength = function(str) {
// <summary>獲得字符串實際長度,中文2,英文1</summary>
// <param name="str">要獲得長度的字符串</param>
var realLength = 0, len = str.length, charCode = -1;
for (var i = 0; i < len; i++) {
charCode = str.charCodeAt(i);
if (charCode >= 0 && charCode <= 128)
realLength += 1;
else
realLength += 2;
}
return realLength;
};
alert(obj.GetLength('這是中文aaaaaaa'));
方法二(更簡潔的方法):
var length = str.length; // str是輸入的字符串 var blen = 0; for (i=0; i<length; i++) { if ((str.charCodeAt(i) & 0xff00) != 0) { // 如果是英文,返回0 blen ++; } blen ++; }
方法三(更更簡潔的方法):
var obj = {}; obj.GetLength = function(str) { // str是輸入的字符串 return str.replace(/[\u0391-\uFFE5]/g,"aa").length; // 先把中文替換成兩個字節的英文,再計算長度 };
alert(obj.GetLength('這是中文aaaaaa'));
TIP:
charCodeAt()方法的作用是:返回指定位置的字符的 Unicode 編碼