html标记响应中的RegEx子字符串显示为null.JS



我有这个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

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中,你可以使用JSDom或Cheerio来实现同样的事情。

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());

无论如何,请不要使用正则表达式来解析HTML。

最新更新