Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sanitize html string except image url?

I'm trying to sanitize an html string, but I want to whitelist image urls. My code:

ActionView::Base.full_sanitizer.sanitize(phrase.meaning, tags: %w(img), attributes: %w(src))

This doesn't work, because it deletes all html tags and the value of src.

My expected result in a json file:

meaning: "Lorem ipsum.... http://localhost/image1.jpg .... Lorem ipsum"
like image 611
Prezes Łukasz Avatar asked Feb 13 '26 02:02

Prezes Łukasz


1 Answers

Perhaps it is easier to use the PermitScrubber from the same gem directly:

html = 'Foo <img src="foo" title="bar"> <a href="foo">bar</a> blob'
scrubber = Rails::Html::PermitScrubber.new
scrubber.tags = ['img']
html_fragment = Loofah.fragment(html)
html_fragment.scrub!(scrubber)
html_fragment.to_s
#=> "Foo <img src=\"foo\" title=\"bar\"> bar blob"
like image 179
spickermann Avatar answered Feb 15 '26 20:02

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!