Modifying text inside html nodes - nokogiri

最后都变了- 提交于 2019-12-03 13:29:15

What about this code?

doc.traverse do |x|
  if x.text?
    x.content = x.content.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*")
  end
end

The traverse method does pretty much the same as search("*").each. Then you check that the node is a Nokogiri::XML::Text and, if so, change the content as you wished.

agmcleod

Thanks to the post here Nokogiri replace tag values, I was able to modify it a bit and figure it out.

doc = Nokogiri::HTML::DocumentFragment.parse(html)
doc.search("*").each do |node|
  dummy = node.add_previous_sibling(Nokogiri::XML::Node.new("dummy", doc))
  dummy.add_previous_sibling(Nokogiri::XML::Text.new(node.to_s.gsub(/(?<=[.!?])(?!\*)/, "#{$1}*"), doc))
  node.remove
  dummy.remove
end

puts doc.to_html.gsub("&lt;", "<").gsub("&gt;", ">")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!