0

I want to encode HTML Scripts.

I have text like this:

"<a href="https://www.w, <script></script>"

I want to only decode

&lt; and &gt; to < and >.

I have a method like this:

def name
  a = [last_name.to_s + ',', first_name].compact.join(' ')
  Loofah.fragment(a).text(encode_special_chars: false) 
end

But using Loofah.fragment it is decoding all html scripts ad showing like this:

"<a href=\"https://www.w, <script></script>" but I want only < and >

Could someone please help me.

Kumar Nikhil
  • 99
  • 1
  • 11
  • Does this answer your question? [How do I encode/decode HTML entities in Ruby?](https://stackoverflow.com/questions/1600526/how-do-i-encode-decode-html-entities-in-ruby) – berkes Jul 25 '23 at 17:36

2 Answers2

0

You can use string replace methods in your case like in the below example:

"&lt;a href=&quot;https://www.w, &lt;script&gt;&lt;/script&gt;".gsub("&lt;","<").gsub("&gt;",">")
greybeard
  • 2,249
  • 8
  • 30
  • 66
0

As mentioned in this Q&A, you can use CGI or Nokogiri:

CGI.unescapeHTML("&lt;a href=&quot;https://www.w, &lt;script&gt;&lt;/script&gt;")

Nokogiri::HTML.parse(""&lt;a href=&quot;https://www.w, &lt;script&gt;&lt;/script&gt;")

But, as mentioned there as well, you are probably not dealing with raw html in the view helpers right.

<%= raw '<html>' %>
berkes
  • 26,996
  • 27
  • 115
  • 206