我正在尝试将文本切成固定长度,但我不想将单词切成两半,所以我需要做这样的事情:
function fixedLength(str, len, bol) {
var i, l = str.length, left = 0, right = l - 1, rtn, tmp;
tmp = str.charAt(len);
if (bol || tmp === " " || tmp === "") {
rtn = str.substr(0, len);
} else {
tmp = len - 1;
for (i = tmp; i > -1; i--) {
if (str.charAt(i) === " ") {
left = i;
break;
}
}
for (i = tmp; i < l; i++) {
if (str.charAt(i) === " ") {
right = i;
break;
}
}
rtn = str.substr(0, ((Math.abs(left - tmp) <= Math.abs(right - tmp)) ? left : right));
}
return rtn + "...";
}
但是当我使用它时:
var str = "the quick brown fox jumped over the lazy dog";
for (var i = 0; i < 45; i++) {
document.write("i:" + i + " - " + fixedLength(str, i) + "<br>");
}
除了这一行之外,每个人似乎都可以正常工作"i:43 - the quick brown fox jumped over the lazy do..."
,“狗”这个词被切成两半(演示)
我找不到漏洞,每次我改变一些东西,我都会添加一个新的错误