Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if String is HTML or not in ruby

Tags:

string

ruby

How can we check the string is HTML or not using Ruby?

If string contains html tag then returns true otherwise false

like image 599
Arvind Kumar Avatar asked Dec 02 '22 15:12

Arvind Kumar


2 Answers

If string contains html tag then returns true otherwise false

This test ("string contains <html>") is not sufficient to determine whether a string is HTML.

How can we check the string is HTML or not using Ruby?

The excellent Nokogiri gem provides HTML validation.

$ gem install nokogiri

require 'nokogiri'

Nokogiri::HTML.parse("<foo>bar</foo>").validate

# => [#<Nokogiri::XML::SyntaxError...>, ...]
like image 119
user513951 Avatar answered Dec 21 '22 23:12

user513951


If you just want to see if a fragment of html is correct without validating tags:

Nokogiri::XML("<foo>bar</foo>").errors.empty?
like image 43
Weston Avatar answered Dec 21 '22 22:12

Weston