缩短50个字符后的文字,但仅在当前单词之后
我需要在50个字符后缩短文字,但是如果第50个字符在一个单词的中间 - 仅在单词之后切下,而不是以前。
示例文本: 与普遍的看法相反,Lorem Ipsum不仅是文本(59个字符)
预期输出:与普遍的看法相反,Lorem Ipsum不仅是(54个字符),
而且我正在尝试: text.substr(0,50).lastIndexof('')); - 对我不利,因为它剪切了“简单的”,我想简单地属于缩短文本。 感谢您的帮助!
I need to shorten text after 50 characters but if the 50th char is at the middle of a word - cut only after the word and not before.
example text:
Contrary to popular belief, Lorem Ipsum is not simply text (59 chars)
expected output: Contrary to popular belief, Lorem Ipsum is not simply (54 chars)
I was trying this:
text.substr(0,50).lastIndexOf(' ')); - not good for me cause it cuts of the "simply" and I want the simply to be at the shorten text.
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果短语长度小于极限,请返回短语;否则,将切片索引设置为极限并扫描,直到找到一个单词边界并切成短语。
If the phrase length is less than the limit, return the phrase; else, set the slice index to the limit and scan until you find a word boundary and slice the phrase.
正则表达可以帮助您。
这个想法是找到至少50个以Word Boundare
\ B
结束的符号upd:
如果要创建一个函数,该函数如果文本超过50个符号,则可以创建一个可以执行此功能而不是您的函数。
然后只是这样使用:
Regular expression can help you with it.
The idea is to find at least 50 symbols that finishes with word boundary
\b
UPD:
If you want to create a function that shorten your text if it's longer than 50 symbols we can create a function that do it instead of you.
Then just use it like that:
您与sudstring&索引。如果您在前50个字符之后寻找空间,则可以使用。然后是一个边缘情况,字符串长于50个字符而没有空间。
You were close with the substring & indexOf. If you look for a space after the first 50 characters it will work. Then there is an edge case where the string is longer then 50 characters and no space.
下一条言论的一线式
一线似乎似乎是多余的,但实际上它们在那里覆盖边缘案例。
无正
测试案例
由于SO内置控制台的局限性, ,请使用F12提升DevTools的控制台,然后然后 运行以下代码以进行一些演示。
Regex one-liners
Parts of the below regexes may seem redundant, but they are actually there to cover the edge cases.
Regex-free
Test cases
Due to the limitations of the SO's built-in console, please first bring up the DevTools's console with F12, and then run the below code for a little demo.