Remove Certain HTML Tags using Ruby

html, html-parsing, regex, ruby

Solution

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>

Problem

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.

Original source

Related problems