instance method
word_wrap
Ruby on Rails 8.1.2
Since v2.2.3Signature
word_wrap(text, line_width: 80, break_sequence: "\n")
Wraps the text into lines no longer than line_width width. This method breaks on the first whitespace character that does not exceed line_width (which is 80 by default).
word_wrap('Once upon a time') # => "Once upon a time" word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...') # => "Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined..." word_wrap('Once upon a time', line_width: 8) # => "Once\nupon a\ntime" word_wrap('Once upon a time', line_width: 1) # => "Once\nupon\na\ntime"
You can also specify a custom break_sequence (“\n” by default):
word_wrap('Once upon a time', line_width: 1, break_sequence: "\r\n") # => "Once\r\nupon\r\na\r\ntime"
Parameters
-
textreq -
line_widthkey = 80 -
break_sequencekey = "\n"
Source
# File actionview/lib/action_view/helpers/text_helper.rb, line 327
def word_wrap(text, line_width: 80, break_sequence: "\n")
return +"" if text.empty?
# Match up to `line_width` characters, followed by one of
# (1) non-newline whitespace plus an optional newline
# (2) the end of the string, ignoring any trailing newlines
# (3) a newline
#
# -OR-
#
# Match an empty line
pattern = /(.{1,#{line_width}})(?:[^\S\n]+\n?|\n*\Z|\n)|\n/
text.gsub(pattern, "\\1#{break_sequence}").chomp!(break_sequence)
end
Defined in actionview/lib/action_view/helpers/text_helper.rb line 327
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in ActionView::Helpers::TextHelper