gpt4 book ai didi

JavaScript 正则表达式将 DIV 与特定类相匹配

转载 作者:行者123 更新时间:2023-12-03 05:04:16 27 4
gpt4 key购买 nike

我正在尝试将正则表达式与 HTML 标签的字符串进行匹配。更准确地说,我有例如:

var myDivs = '<div class="wrapper"><div class="header1">Header1</div></div><div class="wrapper"><div class="header2">Header2</div></div>';

/* Result */
['<div class="wrapper"><div class="header1">Header1</div></div>', '<div class="wrapper"><div class="header2">Header2</div></div>']

我想在我的 Angular2 项目上使用 RegEx 按类“wrapper”过滤此字符串 div。我没有使用 jQuery。

请提供任何帮助。

最佳答案

您不能使用正则表达式来解析 HTML(请参阅 this )。相反,您可以使用 native DOMParser像这样:

function getElements(html, selector) {
var parser = new DOMParser(); // the parser that will parse the html
var dom = parser.parseFromString(html, "text/html"); // parse the text in 'html' as html
var elems = dom.querySelectorAll(selector); // select the elements that match the CSS selector 'selector'
// return their outerHTML (elems is an array like object so map is not defined thus we have to call it in this way)
return Array.prototype.map.call(elems, function(e) {
return e.outerHTML;
});
}


var myDivs = '<div class="wrapper"><div class="header1">Header1</div></div><div class="wrapper"><div class="header2">Header2</div></div>';

console.log(getElements(myDivs, ".wrapper"));

另一种方法:(更好的方法)

您可以将 html 附加到 div,然后仅选择该 div 内的匹配元素:

function getElements(html, selector) {
var div = document.createElement("div"); // the container element
div.innerHTML = html; // set it's html to 'html'
var elems = div.querySelectorAll(selector); // select the elements that match the CSS selector 'selector'
// return their outerHTML (elems is an array like object so map is not defined thus we have to call it in this way)
return Array.prototype.map.call(elems, function(e) {
return e.outerHTML;
});
}


var myDivs = '<div class="wrapper"><div class="header1">Header1</div></div><div class="wrapper"><div class="header2">Header2</div></div>';

console.log(getElements(myDivs, ".wrapper"));

注意:选择器可以是任何内容(任何有效的 CSS Selector )。这样更加灵活。

关于JavaScript 正则表达式将 DIV 与特定类相匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42079639/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com