时间:2021-07-01 10:21:17 帮助过:4人阅读
var str = "aaasssddd";
function cutStr(str, max) {
// 首先把和先给剔除, 然后记录他们的位置
var reg = new RegExp("(.*?)(.*?)(.*?)");
var emSub = str.indexOf("");
var em2Sub = str.indexOf("");
var newstr = str.replace(reg, "$1$2$3");
// 如果不是数字或是负数, 或者大于字符长度, 直接返回原字符
if (!/^\d+$/.test(max) || max >= newstr.length) return str;
newstr = newstr.substring(0, max);
if (max <= emSub) { //小于三
return newstr;
} else if (max <= em2Sub - 4 && max > emSub) { // 大于三, 小于六时(注: -4 是为了减去第一个占去的位置)
var tempReg = new RegExp("(\\w{" + emSub + "})(\\w*?)");
return newstr.replace(tempReg, "$1$2");
} else { // 大于六
var tempReg = new RegExp("(\\w{" + emSub + "})(\\w{" + (em2Sub - emSub - 4) + "}?)(\\w*?)");
return newstr.replace(tempReg, "$1$2$3");
}
}
alert(cutStr(str, 7));?
var str = "aaasssddd";
function cutStr(str, max) {
var emSub = str.indexOf("");
var em2Sub = str.indexOf("");
// 如果不是数字或是负数, 或者大于字符长度, 直接返回原字符
if (!/^\d+$/.test(max) || max >= str.length - 9) return str;
else if(max > em2Sub-4) return str.substring(0, max + 9);
else if(max > emSub) return str.substring(0, max + 4);
else return str.substring(0, max);
}
alert(cutStr(str, 7)); ?