详细

js字符串截取

场景

中文长度为2,英文长度为1,当某段文字长度超过规定的数字时,截取并在后缀处加上省略号。

代码demo

//字符串截取
function strLenDeal(str,len) {
var tempStr,
res,
_strSection = function (strTemp, num) {
var len = 0,
tempArr = [];
for (var i=0; i<strTemp.length; i++) {
if (strTemp.charCodeAt(i)>127 || strTemp.charCodeAt(i)==94) {
len += 2;
} else {
len ++;
}
if(len < num) {
tempArr.push(strTemp.charAt(i));
}
}
if(len > num) {
return tempArr.join('') + '...';
}
return tempArr.join('');
};
if(str.length * 2 < len) {
res = str;
}else if(str.length > len){
tempStr = str.substr(0,len);
res = _strSection(tempStr, len);
}else {
res = _strSection(str, len);
}
return res;
}