如果我理解正确,则希望将字符串缩短为一定的长度(例如,缩短
"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(" ")))}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)