3 回答

TA贡献1946条经验 获得超3个赞
对于像这样的简单问题,有如此之多的答案难以理解,有些答案,包括所选的答案,都不起作用,我感到很惊讶。
我通常希望结果字符串最多为 maxLen字符。我还使用相同的功能来缩短URL中的段。
str.lastIndexOf(searchValue[, fromIndex]) 接受第二个参数,它是开始向后搜索字符串的索引,使事情变得高效而简单。
// Shorten a string to less than maxLen characters without truncating words.
function shorten(str, maxLen, separator = ' ') {
if (str.length <= maxLen) return str;
return str.substr(0, str.lastIndexOf(separator, maxLen));
}
这是一个示例输出:
for (var i = 0; i < 50; i += 3)
console.log(i, shorten("The quick brown fox jumps over the lazy dog", i));
0 ""
3 "The"
6 "The"
9 "The quick"
12 "The quick"
15 "The quick brown"
18 "The quick brown"
21 "The quick brown fox"
24 "The quick brown fox"
27 "The quick brown fox jumps"
30 "The quick brown fox jumps over"
33 "The quick brown fox jumps over"
36 "The quick brown fox jumps over the"
39 "The quick brown fox jumps over the lazy"
42 "The quick brown fox jumps over the lazy"
45 "The quick brown fox jumps over the lazy dog"
48 "The quick brown fox jumps over the lazy dog"
对于子弹:
for (var i = 0; i < 50; i += 10)
console.log(i, shorten("the-quick-brown-fox-jumps-over-the-lazy-dog", i, '-'));
0 ""
10 "the-quick"
20 "the-quick-brown-fox"
30 "the-quick-brown-fox-jumps-over"
40 "the-quick-brown-fox-jumps-over-the-lazy"

TA贡献1817条经验 获得超14个赞
如果我理解正确,则希望将字符串缩短为一定的长度(例如,缩短"The quick brown fox jumps over the lazy dog"为6个字符而不切断任何单词)。
在这种情况下,您可以尝试以下操作:
var yourString = "The quick brown fox jumps over the lazy dog"; //replace with your string.
var maxLength = 6 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
添加回答
举报