为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

长风秋雁 2019-11-07 10:18:10
我对JavaScript中的字符串操作不太满意,我想知道如何在不删节的情况下缩短字符串。我知道如何使用子字符串,但不知道indexOf或其他任何真正好的方法。说我有以下字符串:text = "this is a long string I cant display"我想将其缩减为10个字符,但是如果它不以空格结尾,请完成该单词。我不希望字符串变量看起来像这样:“这是我不能忍受的长字符串”我希望它在出现空格之前将单词结束。
查看完整描述

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"


查看完整回答
反对 回复 2019-11-07
?
大话西游666

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(" ")))


查看完整回答
反对 回复 2019-11-07
  • 3 回答
  • 0 关注
  • 454 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号