html - 显示一定长度的字符串而不截断

标签 html ruby string slice

我在 ruby​​ 中显示一定长度的字符串。一行中只能显示该字符串的 80 个字符。例如,如果字符串长度为 82,那么它将以 2 行显示,如果长度为 250,则字符串将以 5 行等显示,我想在空格而不是单词上拆分。

我是新手,不知道怎么解决。

最佳答案

def wrap(str, max_line_len)
  str.scan /(?<=\A| ).{1,#{max_line_len}}(?= |\z)/
end

str = "Little Miss Muffet she sat on her tuffet, eating her curds and whey. Along " + 
      "came a spider who sat down beside her and frightened Miss Muffet away."

         1         2         3    
123456789012345678901234567890123

puts wrap(str, 31)
Little Miss Muffet she sat on
her tuffet, eating her curds
and whey. Along came a spider
who sat down beside her and
frightened Miss Muffet away.

puts wrap(str, 32)
Little Miss Muffet she sat on
her tuffet, eating her curds and
whey. Along came a spider who
sat down beside her and
frightened Miss Muffet away.

puts wrap(str, 33)
Little Miss Muffet she sat on her
tuffet, eating her curds and
whey. Along came a spider who sat
down beside her and frightened
Miss Muffet away.

参见 String#scan 。正则表达式为“1max_line_len 字符之间的匹配,紧接在字符串的开头或空格之前,紧接着是空格或字符串的结尾”。 (?<=\A| ) 是一个正向后视,而 (?= |\z) 是一个正向前视

关于html - 显示一定长度的字符串而不截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440279/

相关文章:

ruby-on-rails - 离线安装 ruby​​ gems/代理配置

ruby - Ruby Enterprise 是否使用绿色线程?

PHP:如何获取字符串的字符一一

android - 将字符串值转换为字符序列并在android中的通知中显示

html - Bootstrap 中导航和超大屏幕之间的差距

javascript - 使用 Javascript 隐藏然后显示文本 - 过渡不透明度

objective-c - 从 Objective C 调用 Ruby 类/脚本 - MacRuby 是不是太过分了?

ios - 是否可以使用 NSAttributedString 设置多个字体属性

javascript - Google 表单的动态 iframe 高度

javascript - 使用本地存储保存自定义列表显示中的更改