当字数超出规定字数时,可以通过下面函数省略超出的字并且自定义收尾。
比如:
初始表现:你好吗,lily?
规定表现:两个字,多余用 ... 表示
省略表现:你好...
var getNeedStr = (function (window) {
var index = 1;
//计算字符占位(中文为2英文为1)
function judgeLen(str) {
var strLen = 0;
for (let i = 0; i < str.length; i += 1) {
if (str.charCodeAt(i) > 255) {
strLen += 2;
} else {
strLen += 1;
}
}
return strLen;
}
/**
* 主函数
* @param baseStr 基础字符串
* @param number 需要的占位长度(默认英文占位数值)
* @param jointStr 待拼接字符
* @returns {str} 返回字符串
*/
return function (baseStr, number, jointStr) {
var jointStrLen = judgeLen(jointStr);
var strLen = judgeLen(baseStr);
if (strLen > number) {
baseStr = baseStr.replace(jointStr, '');
baseStr = baseStr.slice(0, baseStr.length - 1) + jointStr;
if (index === 1) {
number += jointStrLen;
}
index += 1;
return arguments.callee(baseStr, number, jointStr);
} else {
return baseStr;
}
};
})(window);