使用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正文中获取内容。
领取专属 10元无门槛券
手把手带您无忧上云