mahemoff
mahemoff

Reputation: 46379

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?

Upvotes: 6

Views: 2631

Answers (2)

jvnill
jvnill

Reputation: 29599

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

Upvotes: 2

Niklas B.
Niklas B.

Reputation: 95298

You can use a proper HTML parser to do this. I'd recommend Nokogiri for the job:

require 'nokogiri'
# ...
s = "<a href='http://example.com'>incomplete"
Nokogiri::HTML::fragment(sanitize(s, :tags => ['a', 'p'])).to_xml
# => "<a href=\"http://example.com\">incomplete</a>"

This will always return valid XML. Of course you can package that into your own helper method for easier usage.

Upvotes: 5

Related Questions