微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

是否存在类似于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>

原文地址:https://www.jb51.cc/html/232034.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐