javascript - "HTML tidy"有 JavaScript 或 Ruby 版本吗?

标签 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​​ 中的某些东西对我有用。 谢谢!

最佳答案

在 Ruby 中,您可以在 Nokogiri 中解析 HTML,这将允许您检查错误,然后让它输出 HTML,这将清除丢失的结束标记等。请注意,在以下 HTML 中,title 和 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>

关于javascript - "HTML tidy"有 JavaScript 或 Ruby 版本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4240107/

相关文章:

javascript - 在没有 key 的情况下引用 JS 对象成员

javascript - 使用 jQuery 时 .click() 不起作用

ruby-on-rails - 从 csv 文件导入数据时无法批量分配 protected 属性

ruby-on-rails - rails : working with calculated values

php - 在不刷新的情况下更新标签内的变量

javascript - angularjs 中的日期在 $resource.$save() 中以 UTC 发送

javascript - 将默认日期转换为另一个日期(用户的本地时区)

javascript - jquery UI 模式不会导致回发

ruby-on-rails - 通过按钮调用 Ruby 方法

javascript - 在 Jest 中模拟静态方法