Reputation: 989
I am using Nokogiri in a Rails 3 app. It ignores
<br/>
tags. I'd like to replace such tags with ", " because they represent line breaks in addresses. How do I do this? I've tried the following, which doesn't seem to help:
doc.inner_html.gsub!("<br/>", ", ")
Upvotes: 4
Views: 3279
Reputation: 303215
Simply:
doc.css('br').each{ |br| br.replace ", " }
Seen in action:
require 'nokogiri'
doc = Nokogiri.HTML('<address>900 Magnolia Road<br/>Nederland, CO<br/>80466</address>')
puts doc.root
#=> <html><body><address>900 Magnolia Road<br>Nederland, CO<br>80466</address></body></html>
doc.css('br').each{ |br| br.replace ", " }
puts doc.root
#=> <html><body><address>900 Magnolia Road, Nederland, CO, 80466</address></body></html>
If you want to be more careful and only replace the <br>
inside an <address>
tag (for example), then:
doc.css('address > br').each{ |br| br.replace ", " }
Upvotes: 11
Reputation: 12273
Set the content like so:
doc.inner_html = doc.inner_html.gsub("<br/>", ", ") # using non-bang version
Upvotes: 0