Does anybody have any code handy that center truncates a string in Ruby on Rails?
Something like this: Ex: "Hello World, how are you?" => "Hel...you?"
Truncate the string (first argument) if it is longer than the given maximum string length (second argument) and return the truncated string with a ... ending. The inserted three dots at the end should also add to the string length.
Using String's split() Method. Another way to truncate a String is to use the split() method, which uses a regular expression to split the String into pieces. The first element of results will either be our truncated String, or the original String if length was longer than text.
Solution # 1: Truncate text for single line This solution works for single-line truncation. Force text to be on a single line: white-space: nowrap; Now, our text should be on the same line and should overflow from the box if it's long enough and wrapped before.
If you want a certain fixed length irrespective of the length of the string, you can use Rails #truncate
:
s.truncate(100, omission: "...#{s.last(50)}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With