Rails - How to only escape – Laas Mar 01 '16 at 09:38

4 Answers4

1

As you are on rails 4.2.5, you can use https://github.com/rails/rails-html-sanitizer which gets installed with rails. You can do following to escape only script tag.

scrubber = Rails::Html::TargetScrubber.new
scrubber.tags = ['script']

html_fragment = Loofah.fragment('<script></script><div></div>')
html_fragment.scrub!(scrubber)
html_fragment.to_s # outputs "<div></div>"
BananaNeil
  • 10,322
  • 7
  • 46
  • 66
Rohan Pujari
  • 788
  • 9
  • 21
0
 string = '<html> <title> <head> <script type="javascript"></script> </head> </title> </html>'

 string.gsub(/<script.*[\s\S]*\/script>/,"")

 => "<html> <title> <head>  </head> </title> </html>"

Update

If you are using Rails 4.2.5 you may need this.

Rails::HTML::TargetScrubber

Rubysmith
  • 1,165
  • 8
  • 12
0

Rails providing so many options for string / HTML entities

  s = "<script>alert('Hello');</script>"  

option : WhiteListSanitizer

 white_list_sanitizer = Rails::Html::WhiteListSanitizer.new
 white_list_sanitizer.sanitize(s, tags: %w())
 white_list_sanitizer.sanitize(s, tags: %w(table tr td), attributes: %w(id class style))
  => "alert('Hello');"

Refer this link alse

How to show some HTML entities on title tag using Rails

Community
  • 1
  • 1
Kanna
  • 990
  • 1
  • 11
  • 30
-2
string.gsub!(/<(?=script)||(?<=script)>/) {|x| "#\{x}"}
Joe Half Face
  • 2,303
  • 1
  • 17
  • 45