在 rails 中的单词中间截断字符串而不剪切 [英] Truncate a string without cut in the middle of a word in rails
本文介绍了在 rails 中的单词中间截断字符串而不剪切的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将文本截断到最近的位置,并且在没有在单词中间切割的情况下使用 rails 3?
How can i truncate a text to the closest position with rails 3 whithout cut in the middle of a word?
例如,我有字符串:
"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 ..."
而不是:
"Praesent commodo cursus magna, vel scelerisque nisl conse..."
推荐答案
如果您将分隔符传递给 truncate 方法,它将执行自然分词而不是在单词中间截断
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
这样的事情应该可以工作(如果您想要默认的 30 个字符,请将长度更改为您想要完全删除的长度):
Something like this should work (vary the length to whatever you want to remove it altogether if you want the default of 30 characters):
truncate("Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum.", :length => 17, :separator => ' ')
有关截断选项的更多信息,请参见 文档
More information about the options you can have in truncate can be found in the Documentation
这篇关于在 rails 中的单词中间截断字符串而不剪切的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文