Search code examples
htmlruby-on-railsrubyescapingstring-conversion

How to do the "inverse" of Rails' simple_format?


The simple_format helper in Rails will take text input and convert newline characters to p or br tags which is the exact opposite of what I'm trying to accomplish.

How would i go about taking a snippet of HTML that looks like:

<p>Lorem</p>
<p>Ipsum.
  <br /> 
  Lorem ipsum.
  <br /> 
  Lorem ipsum. 
</p>
<p>
  Lorem ipsum.
</p>

And convert it to something that looks like:

Lorem\n\nIpsum.\nLorem ipsum.\nLorem ipsum.\n\nLorem ipsum.

Solution

  • new_html = html
                 .gsub("\n", '')             # remove existing new lines
                 .gsub('</p>', "</p>\n")     # add a new line per para tag
                 .gsub('<br />', "<br />\n") # add a new line per break tag
    ActionController::Base.helpers
      .strip_tags(new_html)                  # remove all html tags