Nokogiri Returning False on Empty String With .empty?

Viewed 111

I'm trying to remove empty <p> tags from a document using Nokogiri based gem, ruby-readability. Using .strip.empty? in the console is working fine like this:

irb> p = Nokogiri::HTML("<p> </p>")
=> #<Nokogiri::HTML::Document...
irb> p.content
=> " "
irb> p.content.strip
=> ""
irb> p.content.strip.empty?
=> true

Running that same operation inside the ruby-readability gem, is returning false.

Inside that method I've added an extra call to test the <p> </p> line in my test HTML document:

if @options[:remove_empty_nodes]
  node.css("p").each do |elem|
    puts "IS IT EMPTY?"
    puts element.content.strip.empty?
    elem.remove if elem.content.strip.empty?
  end
end
IS IT EMPTY?
false

Why is this returning false?

Update:

Per the descussion below I added a new element to the HTML document: <p></p>. If I call element.content.bytes.inspect or element.content.strip.bytes.inspect I get this:

ELEMENT:
<p> </p>
[194, 160]
ELEMENT:
<p></p>
[]

In IRB, .strip seems to be working:

irb> p.content.bytes.inspect
=> "[32]"
irb> p.content.strip.bytes.inspect
=> "[]"
1 Answers

32 decimal is 0x20 in hex or "\u0020", that's a single space in UTF-8 and String#strip knows what to do with it. The bytes [194, 160] are "\u00a0" which is a non-breaking space: it looks like a space but String#strip won't recognize it as whitespace because:

Whitespace is defined as any of the following characters: null, horizontal tab, line feed, vertical tab, form feed, carriage return, space.

You could use the whitespace character property instead of #strip:

elem.remove if elem.content.gsub(/\p{Space}/, '').empty?
Related