使用JavaScript和正则表达式获取HTML正文中的内容可以通过以下几个步骤实现:
DOMParser
对象实现这一功能。const parser = new DOMParser();
const htmlDoc = parser.parseFromString(htmlString, 'text/html');
textContent
属性获取节点中的文本内容,然后使用match()
方法和正则表达式来匹配所需的内容。const textContent = htmlDoc.body.textContent;
const regex = /需要匹配的正则表达式/;
const matchedContent = textContent.match(regex);
const result = [];
if (matchedContent) {
result.push(matchedContent);
}
完整的代码示例如下:
function getContentFromHtml(htmlString, regex) {
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(htmlString, 'text/html');
const textContent = htmlDoc.body.textContent;
const matchedContent = textContent.match(regex);
const result = [];
if (matchedContent) {
result.push(matchedContent);
}
return result;
}
const htmlString = '<div><p>这是一段文本。</p><p>这是另一段文本。</p></div>';
const regex = /文本/g;
const content = getContentFromHtml(htmlString, regex);
console.log(content);
这个示例中,我们定义了一个getContentFromHtml
函数,该函数接受HTML字符串和正则表达式作为参数,并返回匹配到的内容。在这个示例中,我们使用了<div>
和<p>
标签来演示如何从HTML正文中获取内容。
腾讯云GAME-TECH游戏开发者技术沙龙
大匠光临
企业创新在线学堂
云+社区沙龙online第5期[架构演进]
腾讯云GAME-TECH游戏开发者技术沙龙
云+社区技术沙龙[第5期]
云+社区技术沙龙[第28期]
第五届Techo TVP开发者峰会
云+社区技术沙龙[第6期]
腾讯位置服务技术沙龙
腾讯云GAME-TECH游戏开发者技术沙龙
领取专属 10元无门槛券
手把手带您无忧上云