htmlruby-on-railsrubyruby-on-rails-3.1sanitize

Sanitize HTML and close incomplete tags


sanitize() in ApplicationHelper doesn't close tags.

s = "<a href='http://example.com'>incomplete"
sanitize(s, :tags => ['a', 'p'])

The above snippet leaves the string as is. How could I force it to append a closing </a> or at least strip the <a> altogether?


Solution

  • The updated answer is

     s = "<a href='http://example.com'>incomplete"
     html = sanitize(s, tags: %w[a p])
     Nokogiri::HTML::DocumentFragment.parse(html).to_html