【问题标题】:RegEx substring from html tag response, shows null. JS [duplicate]来自 html 标记响应的正则表达式子字符串显示为空。 JS [重复]
【发布时间】:2021-07-21 19:22:54
【问题描述】:

我有这个 html 字符串

<span style="font-size:25px;border-radius: 10px;">John Doe</span>

来自回复。我尝试使用此代码仅获取 John Doe

const testt = String(response.body)  
const match = testt.match(/^<span style="font-size:25px;border-radius: 10px;">(.*)<\/span>$/);
console.log('match', match[1]);

我在日志中收到null

【问题讨论】:

  • 它周围可能有额外的空白。试试test1 = response.body.trim()

标签: javascript html string match response


【解决方案1】:

JS 已经有了 HTML 解析器,为什么不用呢?

const html = `
  <span style="font-size:25px;border-radius: 10px;">John Doe</span>
`;

const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
console.log(doc.querySelector("span").textContent);

// or attach to another element
const root = document.createElement("div");
root.innerHTML = html;
console.log(root.querySelector("span").textContent);

如果您在 Node 中,则可以使用 JSDomCheerio 来实现相同的目的。

const cheerio = require("cheerio");

const html = `
  <span style="font-size:25px;border-radius: 10px;">John Doe</span>
`;
const $ = cheerio.load(html);
console.log($("span").text());

不管怎样,请don't use regex to parse HTML

【讨论】:

  • (在节点中)响应数据中还有其他&lt;span&gt; 标签。因为我使用了String(),所以我只在响应中显示了我需要的字符串
  • 您需要提供更多信息来区分一个跨度标签和另一个标签。请编辑您的帖子以显示更大的 HTML sn-p,或提供我可以检查的实时 URL。通常,如果跨度中的所有内容都是一些内联样式,则通常是父标签通常具有可预测的结构或可使用的类/ID。然而,无论有什么区别特征,HTML 解析器都具有比任何其他工具更好地区分的能力。另外,请澄清浏览器JS或Node。
猜你喜欢
  • 1970-01-01
  • 2020-01-30
  • 2021-01-12
  • 1970-01-01
  • 2020-05-06
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
相关资源
最近更新 更多