html - Issue with gsub method in my Ruby code when trying to replace HTML tags with the URL stripped from in it
问题描述
解决方案
Because Nokogiri::XML::Element
is neither a string nor a regexp. Sticking .to_s
works:
puts message.gsub(
Nokogiri::HTML.parse(message).at('a').to_s,
Nokogiri::HTML.parse(message).at('a')['href']
)
However, you are going to all the trouble of parsing the HTML just to search the document again as if you didn't know anything about it. Also, it will give a wrong result if you have multiple links in one message, or if your anchor tag is not formatted canonically — e.g. if you have an extra space, like this: <a href="https://www.google.com" >https://www.google.com</a>
Why not let Nokogiri work?
puts Nokogiri::HTML.fragment(message).tap { |doc|
doc.css("a").each { |node|
node.replace(node["href"])
}
}.to_html
Note that I changed Nokogiri::HTML.fragment
, since this is not a full HTML document (with doctype and all), which Nokogiri would feel obligated to add. Then, for each anchor node, replace it with the value of its href
attribute.
推荐阅读
- dart - 仅在飞镖中向 API 发出 HTTP 获取请求?
- node.js - 从 GCP App Engine(nodejs,标准环境)到 Mongodb Atlas 的 VPC 对等问题
- r - 如果 if 语句为假,则在 R 中什么都不做?
- nuxt.js - 如何在 Nuxt.js 中使用 Google 标签
- java - 带有子句“where value in (select id from otherTable)”的 Spring JPA 查询
- spring - 不推荐使用 EnableBinding 类型,不推荐使用 StreamListener 类型 - Spring Cloud Stream
- javascript - 使用 TypeOrm 在数据库中添加新数据
- javascript - ReferenceError: 没有使用 require("dotenv").config();
- c++ - 您可以使用 C++ 指针的范围有哪些?
- reactjs - 如何使用离子反应创建输入自动建议或选择选项搜索?