Modifying text inside html nodes - nokogiri

前端 未结 2 1186
自闭症患者
自闭症患者 2021-02-15 14:14

Let\'s say i have the following HTML:

  • Bullet 1.
  • Bullet 2.
  • Bullet 3.
  • Bullet 4.&
2条回答
  •  不要未来只要你来
    2021-02-15 14:39

    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("<", "<").gsub(">", ">")
    

提交回复
热议问题