猿问

缩短字符串而无需在JavaScript中切词

我对JavaScript中的字符串操作不太满意,我想知道如何在不删节的情况下缩短字符串。我知道如何使用子字符串,但不知道indexOf或其他任何真正好的方法。


说我有以下字符串:


text = "this is a long string I cant display"

我想将其缩减为10个字符,但是如果它不以空格结尾,请完成该单词。我不希望字符串变量看起来像这样:


“这是我不能忍受的长字符串”


我希望它在出现空格之前将单词结束。


长风秋雁
浏览 455回答 3
3回答

智慧大石

对于像这样的简单问题,有如此之多的答案难以理解,有些答案,包括所选的答案,都不起作用,我感到很惊讶。我通常希望结果字符串最多为 maxLen字符。我还使用相同的功能来缩短URL中的段。str.lastIndexOf(searchValue[, fromIndex]) 接受第二个参数,它是开始向后搜索字符串的索引,使事情变得高效而简单。// Shorten a string to less than maxLen characters without truncating words.function shorten(str, maxLen, separator = ' ') {&nbsp; if (str.length <= maxLen) return str;&nbsp; return str.substr(0, str.lastIndexOf(separator, maxLen));}这是一个示例输出:for (var i = 0; i < 50; i += 3)&nbsp;&nbsp; console.log(i, shorten("The quick brown fox jumps over the lazy dog", i));&nbsp;0 ""&nbsp;3 "The"&nbsp;6 "The"&nbsp;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)&nbsp;&nbsp; console.log(i, shorten("the-quick-brown-fox-jumps-over-the-lazy-dog", i, '-'));&nbsp;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"

大话西游666

如果我理解正确,则希望将字符串缩短为一定的长度(例如,缩短"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 lengthvar trimmedString = yourString.substr(0, maxLength);//re-trim if we are in the middle of a wordtrimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答