Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Certain HTML Tags using Ruby

How can I remove certain HTML tags by name in Ruby?

For example:

string = "<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>"

string.magic_method("h1") #=> "<!DOCTYPE html><html><body><p>My first paragraph.</p></body></html>"

I wrote some regex to do this but wondered if there was a library or native method that could do the same thing.

like image 361
Dru Avatar asked Aug 16 '26 13:08

Dru


2 Answers

Using Nokogiri:

require 'nokogiri'

doc = Nokogiri::HTML <<-_HTML_
<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>
_HTML_

doc.at('h1')
# => #(Element:0x4d2f006 {
#      name = "h1",
#      children = [ #(Text "My First Heading")]
#      })

doc.at('h1').unlink
puts doc.to_html
# >> <!DOCTYPE html>
# >> <html><body><p>My first paragraph.</p></body></html>
like image 189
Arup Rakshit Avatar answered Aug 19 '26 11:08

Arup Rakshit


Use the gem nokogiri. It has some nice methods to manipulate HTML and XML, including one that removes tags as you can see here: How do I remove a node with Nokogiri?

Github: https://github.com/sparklemotion/nokogiri

like image 25
MurifoX Avatar answered Aug 19 '26 11:08

MurifoX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!