仅从字符串中删除锚标记

时间:2016-03-12 07:11:47

标签: ruby ruby-on-rails-4 sanitize

在控制器中:

str= "Employee <b><a href=http://xyz.localhost.in:3000/admin/company>Uday Das</a></b> has applied for leave."

我想从上面的字符串中删除锚标记,例如Employee <b>Uday Das</b> has applied for leave.

我使用了这段代码:

ActionView::Base.full_sanitizer.sanitize(str)

但它会从字符串中删除所有html标记,因此我得到Employee Uday Das has applied for leave.

注意:我收到的是动态字符串,锚标记位置不固定,可能是字符串中的任何位置。

3 个答案:

答案 0 :(得分:4)

您可以使用nokogiri gem。

类似的东西:

require 'nokogiri'
doc = Nokogiri::HTML str
node = doc.at("a")
node.replace(node.text)

puts puts doc.inner_html
# <html><body><p>Employee <b>Uday Das</b> has applied for leave.</p></body></html>

或匹配您的确切输出:

puts doc.at("p").inner_html
# Employee <b>Uday Das</b> has applied for leave.

答案 1 :(得分:1)

我得到了一个简单的解决方案:

include ActionView::Helpers::SanitizeHelper
sanitize(str, :tags=>["b"])

答案 2 :(得分:0)

对于链接,您可以使用strip_links中的ActionView::Helpers::SanitizeHelper方法

strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>')
# => Ruby on Rails

strip_links('Please e-mail me at <a href="mailto:me@email.com">me@email.com</a>.')
# => Please e-mail me at me@email.com.

strip_links('Blog: <a href="http://www.myblog.com/" class="nav" target=\"_blank\">Visit</a>.')
# => Blog: Visit.

strip_links('<<a href="https://example.org">malformed & link</a>')
# => <malformed & link