Truncate a string without cut in the middle of a word in rails

孤人 提交于 2019-12-18 12:52:46

问题


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..."

回答1:


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):

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




回答2:


Truncate is a great option, but if you want to have complete word detection, regex is your solution. I would recommend something like this:

string.match(/^.{0,30}\b/)[0]

Or you can put this in a function

def shorten(string, count)
  string.match(/^.{0,#{count}}\b/)[0]
end

Update

According to Rails documentation, you can pass regex into the truncate method, like so:

'Once upon a time in a world far far away'.truncate(27, separator: /\s/)

Both of these options offer far better word boundary detection than passing in a space character into the truncate method.




回答3:


Starting Rails 4.2 there is a new ActiveSupport method called string#truncate_words. It truncates a string by number of words which makes it impossible to have a cut in the middle of a word.

'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')

which returns

"And they found that many... (continued)"


来源:https://stackoverflow.com/questions/8714045/truncate-a-string-without-cut-in-the-middle-of-a-word-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!