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

缩短字符串而无需在JavaScript中切词,第1张

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

如果我理解正确,则希望将字符串缩短为一定的长度(例如,缩短

"The quick brown fox jumps over the lazydog"
为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 and re-trim only when necessary (prevent re-trim when string is shorted than maxLength, it causes last word cut) if(yourString.length > trimmedString.length){    //trim the string to the maximum length    var trimmedString = yourString.substr(0, maxLength);    //re-trim if we are in the middle of a word and     trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4976035.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-14
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存