Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..."
like image 253
Sebastien Avatar asked Jan 03 '12 14:01

Sebastien


3 Answers

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

like image 108
Suhail Patel Avatar answered Nov 16 '22 21:11

Suhail Patel


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)"
like image 20
Oss Avatar answered Nov 16 '22 19:11

Oss


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.

like image 7
Nick Gronow Avatar answered Nov 16 '22 19:11

Nick Gronow