Dom*_*Dom 0 ruby ruby-on-rails ruby-on-rails-4
HTML
<p>Hello</p>
<p>this is <br></p>
<p>a <br></p>
<p>test message</p><br>
Run Code Online (Sandbox Code Playgroud)
我已经尝试过'strip tags',它给了我以下输出:“Hellothis is a test message”
我想要的输出:
Hello
this is
a
test message
Run Code Online (Sandbox Code Playgroud)
html = "<p>Hello</p>
<p>this is <br></p>
<p>a <br></p>
<p>test message</p><br>"
Run Code Online (Sandbox Code Playgroud)
strip_tags 助手似乎工作正常:
puts ActionController::Base.helpers.strip_tags(html)
# =>
# Hello
# this is
# a
# test message
Run Code Online (Sandbox Code Playgroud)
Nokogiri 默认情况下包含在 Rails 中,因此您也可以使用:
doc = Nokogiri::HTML(html)
puts doc.xpath("//text()").to_s
Run Code Online (Sandbox Code Playgroud)
它输出:
Hello
this is
a
test message
Run Code Online (Sandbox Code Playgroud)
如果要删除换行符:
ActionController::Base.helpers.strip_tags(html).gsub(/\s+/,' ')
#=> "Hello this is a test message"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2650 次 |
| 最近记录: |