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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With