我不太擅长 JavaScript 中的字符串操作,我想知道如何在不删掉任何单词的情况下缩短字符串。我知道如何使用子字符串,但不知道如何使用 indexOf 或其他任何东西。
假设我有以下字符串:
text = "this is a long string I cant display"
我想将它缩减为 10 个字符,但如果它没有以空格结尾,请完成这个词。我不希望字符串变量看起来像这样:
"this is a long string I cant dis"
我希望它完成单词直到出现空格。
最佳答案
如果我理解正确,你想将字符串缩短到一定长度(例如,将 "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(" ")))
关于javascript - 缩短字符串而不切割 JavaScript 中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5454235/