截断字符串而不在 Rails 中的单词中间进行切割
如何使用 Rails 3 将文本截断到最近的位置而不在单词中间进行剪切?
例如,我有字符串:
"Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum."
如果我剪它,我想像这样剪:
"Praesent commodo cursus magna, vel scelerisque nisl ..."
而不是:
"Praesent commodo cursus magna, vel scelerisque nisl conse..."
How can i truncate a text to the closest position with rails 3 whithout cut in the middle of a word?
For exemple, I have the string :
"Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum."
If i cut it, i want to cut like this :
"Praesent commodo cursus magna, vel scelerisque nisl ..."
And not :
"Praesent commodo cursus magna, vel scelerisque nisl conse..."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您将分隔符传递给 truncate 方法,它将执行自然的分词,而不是在单词中间截断
类似这样的东西应该可以工作(如果您想要默认值 30,则可以将长度更改为您想要的值,将其完全删除)字符):
有关截断选项的更多信息可以在 文档
If you pass in a separator to the truncate method it will perform a natural word break instead of truncating at a middle of a word
Something like this should work (vary the length to whatever you want to remove it altogether if you want the default of 30 characters):
More information about the options you can have in truncate can be found in the Documentation
从
Rails 4.2
开始,有一个新的ActiveSupport
方法,名为 <代码>string#truncate_words。它按单词数截断字符串,这使得不可能在单词中间进行剪切。返回
Starting
Rails 4.2
there is a newActiveSupport
method calledstring#truncate_words
. It truncates a string by number of words which makes it impossible to have a cut in the middle of a word.which returns
截断是一个不错的选择,但如果您想要完整的单词检测,正则表达式就是您的解决方案。我会推荐这样的东西:
或者你可以把它放在一个函数中
更新
根据 Rails 文档,您可以将正则表达式传递到 truncate 方法中,如下所示:
这两个选项都比将空格字符传递到 truncate 方法中提供更好的单词边界检测。
Truncate is a great option, but if you want to have complete word detection, regex is your solution. I would recommend something like this:
Or you can put this in a function
Update
According to Rails documentation, you can pass regex into the truncate method, like so:
Both of these options offer far better word boundary detection than passing in a space character into the truncate method.