繁体   English   中英

在句子中截断句子?

[英]Truncate sentences in rails?

我有一个用来在Rails中截断字符串的助手,当我截断以句点结尾的句子时,它非常有用。 当句子以问号或感叹号结尾时,我该如何修改代码以截断句子?

def smart_truncate(s, opts = {})
    opts = {:words => 12}.merge(opts)
    if opts[:sentences]
      return s.split(/\.(\s|$)+/).reject{ |s| s.strip.empty? }[0, opts[:sentences]].map{|s| s.strip}.join('. ') + '...'
    end
    a = s.split(/\s/) # or /[ ]+/ to only split on spaces
    n = opts[:words]
    a[0...n].join(' ') + (a.size > n ? '... (more)' : '')
end

谢谢!!!

你有truncate方法

'Once upon a time in a world far far away'.truncate(27, separator: /\s/, ommission: "....")

它将返回"Once upon a time in a..."


而且,如果您需要按字数截断,则可以使用新引入的truncate_words (从Rails 4.2.2开始)

'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')

哪个返回

"And they found that many... (continued)"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM