是否有“HTML整洁”的JavaScript或Ruby版本?

时间:2010-11-21 20:16:53

标签: javascript jquery ruby-on-rails ruby tidy

是否存在类似于HTML tidy(http://tidy.sourceforge.net/)的库,该库不是特定于操作系统的(需要在每个主机上编译)。基本上我只想验证/清理用户发送给我的HTML。

<p>hello</p></p><br>

应该成为

<p>hello</p>
<br/>

javascript或ruby中的东西对我有用。 谢谢!

6 个答案:

答案 0 :(得分:1)

你之前检查了吗? http://tidy.rubyforge.org/

答案 1 :(得分:1)

在Ruby中,您可以解析Nokogiri中的HTML,它可以让您检查错误,然后输出HTML,这将清除丢失的结束标记等。请注意,在以下HTML中,标题和p标签未正确关闭,但Nokogiri添加了结束标记。

require 'nokogiri'

html = '<html><head><title>the title</head><body><p>a paragraph</body></html>'
doc = Nokogiri::HTML(html)
puts "Errors found" if (doc.errors.any?)
puts doc.to_html
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> <html>
# >> <head>
# >> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
# >> <title>the title</title>
# >> </head>
# >> <body><p>a paragraph</p></body>
# >> </html>

或者,您可以打开与/usr/bin/tidy的连接并告诉它进行肮脏的工作:

require 'open3'

html = '<html><head><title>the title</head><body><p>a paragraph</body></html>'

stdin, stdout, stderr = Open3.popen3('/usr/bin/tidy -qi')
stdin.puts html
stdin.close
puts stdout.read
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
# >> 
# >> <html>
# >> <head>
# >>   <meta name="generator" content=
# >>   "HTML Tidy for Mac OS X (vers 31 October 2006 - Apple Inc. build 15.3.6), see www.w3.org">
# >> 
# >>   <title>the title</title>
# >> </head>
# >> 
# >> <body>
# >>   <p>a paragraph</p>
# >> </body>
# >> </html>

答案 2 :(得分:1)

html-tidy已编译为javascript(使用emscripten)。

请参阅the demo并下载tidy.js

如果你足够勇敢,可以使用你想要的选项自己编译成javascript。见https://github.com/lovasoa/tidy-html5

答案 3 :(得分:0)

有一个java端口JTidy但是没有其他我知道的端口,可能有一些方法你从Ruby调用HTML整洁适合你,prahaps在你的命令行调用html整洁的应用程序ruby webapp。

答案 4 :(得分:0)

W3 Validator会为你工作吗?

或者您是否想要修复错误?

答案 5 :(得分:0)

如果你只想要一个美化师使用Pretty Diff。

http://prettydiff.com/?m=beautify&html