Sebastien
Sebastien

Reputation: 6660

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

Upvotes: 25

Views: 15484

Answers (3)

Oss
Oss

Reputation: 4320

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

Upvotes: 10

Nick Gronow
Nick Gronow

Reputation: 1617

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.

Upvotes: 8

Suhail Patel
Suhail Patel

Reputation: 13694

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

Upvotes: 51

Related Questions