title: Rails 5 - How to strip tags from string in rails (NOT in/for html)
body: <p>I need to strip tags from user input before saving into DB</p>
  <p>I'm well aware of strip_tags method but it also html escapes string, as well as all other recommended methods:</p>
  <pre><code>Rails::Html::FullSanitizer.new.sanitize '&amp;'
   =&gt; &quot;&amp;amp;&quot; 
  Rails::Html::WhiteListSanitizer.new.sanitize('&amp;', tags: [])
   =&gt; &quot;&amp;amp;&quot; 
  ActionController::Base.helpers.strip_tags &quot;&amp;&quot;
   =&gt; &quot;&amp;amp;&quot; 
  
  </code></pre>
  <p>The string I want to sanitize is NOT to be escaped, it's getting exported via API, used in files etc. it's NOT only outputted via HTML (where also in cases like <code>link_to ActionController::Base.helpers.strip_tags(&quot;&amp;&quot;)</code> - link_to is double escaping string so you'll get link to <code>&amp;amp;</code> in the frontend )</p>
  <p>As a monkey patch I've wrapped strip_tags into <code>CGI.unescapeHTML</code> to get more or less expected result but want to find some straight solution (I'm also afraid what else can strip_tags do and there are too many moving parts for that small functionality - more stuff that can go wrong or become broken)</p>
  <p>Real world example:
  <code>JPMorgan Chase &amp; Co</code> should become <code>JPMorgan Chase &amp; Co</code> after removing tags</p>
  <p><code>test&lt;script&gt;alert('hacked!');&lt;/script&gt;&amp;test</code> should become <code>test&amp;test</code> after stripping tags</p>
  <p>And also string:</p>
  <pre><code>&quot;test &amp;#x3C;script&amp;#x3E;alert(&amp;#x27;hacked!&amp;#x27;)&amp;#x3C;/script&amp;#x3E;&quot;
  </code></pre>
  <p>Should still be</p>
  <pre><code>&quot;test &amp;#x3C;script&amp;#x3E;alert(&amp;#x27;hacked!&amp;#x27;)&amp;#x3C;/script&amp;#x3E;&quot;
  </code></pre>
  <p>After stripping HTMLs</p>
  <p>With alternative solutions that I've found or that was proposed:</p>
  <pre><code>&gt; Nokogiri::HTML(&quot;test &amp;#x3C;script&amp;#x3E;alert(&amp;#x27;hacked!&amp;#x27;)&amp;#x3C;/script&amp;#x3E;&quot;).text
   =&gt; &quot;test &lt;script&gt;alert('hacked!')&lt;/script&gt;&quot;
  
  &gt; Loofah.fragment(&quot;test &amp;#x3C;script&amp;#x3E;alert(&amp;#x27;hacked!&amp;#x27;)&amp;#x3C;/script&amp;#x3E;&quot;).text(encode_special_chars: false)
   =&gt; &quot;test &lt;script&gt;alert('hacked!')&lt;/script&gt;&quot;
  
  </code></pre>
  <p>So they're also a no go</p>