【发布时间】:2014-09-30 02:51:11
【问题描述】:
给定这个变量:
=> str = " and then there was a gigantic <a href="link.com/bug.jpg">bug</a> on her nose!"
如何编写一个函数,而不是像这样在达到字符限制的地方中断:
=> str[0..33] = " and then there was a gigantic <a "
我有一些可以很好地与 HTML 配合使用的东西,如果打开标签,则返回结束标签:
=> some_function(str) = " and then there was a gigantic <a href="link.com/bug.jpg">bug</a>"
我什至会满足于返回更糟糕的东西,例如:
=> worse_function(str) = " and then there was a gigantic"
任何帮助都会很棒。显然它必须有一个粗略的字符限制,甚至是字数限制。
更新
到目前为止,我有这个:
def friendly_excerpt(string, length)
excerpt = string.split[0..length].to_s
if excerpt.include?('<') && !excerpt.include?('>')
friendly_excerpt = excerpt.slice(0..(excerpt.index('<')))
end
friendly_excerpt
end
【问题讨论】:
-
你目前得到的代码在哪里?
标签: html ruby-on-rails regex ruby-on-rails-3