Search code examples
ruby-on-railsrubyline-breakswhatsappuriencoding

Ruby: Convert <br> to newline URI encode


I want to share sometext on whatsapp so I'm converting html to text otherwise it displays all the tags.

Currently I'm using strip_tags to remove tags but that also removes breaks from the text. How do I convert html to text and convert breaks to newline characters and url encode the text.

currently I'm using following

@whatsapp_text = u strip_tags(@post.summary)

Solution

  • I suggest you tu use Nokogiri to solve this problem. Nokogiri can parse HTML and convert Websites Source into human readable text although it doiesnt convert html breaks to linebreaks it can take away many problems from you. To do this add the follofing line to your Gemfile

    gem 'nokogiri'
    

    run bundle install. Then you can solve your problem like this:

    Nokogiri::HTML.parse(@post.summary.gsub("<br>", "\r\n").gsub("<br/>", "\r\n")).inner_text
    

    That should do it for you.