首先是计算问题,我爱模板网在网上找到了下面几个方法,都还不错:
方法一:
String.prototype.gblen = function() { var len = 0; for (var i=0; i<this.length; i++) { if (this.charCodeAt(i)>127 || this.charCodeAt(i)==94) { len += 2; } else { len ++; } } return len; }方法二:
function strlen(str){ var len = 0; for (var i=0; i<str.length; i++) { var c = str.charCodeAt(i); //单字节加1 if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) { len++; } else { len+=2; } } return len; }方法三:
var jmz = {}; jmz.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; };方法四:
var l = str.length; var blen = 0; for(i=0; i<l; i++) { if ((str.charCodeAt(i) & 0xff00) != 0) { blen ++; } blen ++; }方法五:把双字节的替换成两个单字节的然后再获得长度
getBLen = function(str) {
if (str == null) return 0;
if (typeof str != "string"){
str += "";
}
return str.replace(/[^\x00-\xff]/g,"01").length;
}
至于实现字符超出截断,请看下面代码:
<input placeholder="在此输入备注" value="{{value}}" focus="true" bindinput="inputValue" maxlength="20"></input> data: { value: '', valueLength:0, }, inputValue: function (e) { var val = e.detail.value; var len = this.strlen(val); if(len>20){ val = val.substring(0, this.strAt(val)); } this.setData({ valueLength: this.strlen(val), value: val, showClear: val.length>0 }) }, strlen: function(str){ var len = 0; for(var i = 0; i<str.length; i++) { var c = str.charCodeAt(i); if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) { len++; } else { len += 2; } } return len; }, //计算超过20的那个字符所在的索引 strAt(str){ var pos = 0; var len = 0; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) { len++; } else { len += 2; } if(len>20){ return pos; }else{ pos++; } } },