我正在尝试将带有HTML标记的字符串的RegEx匹配。更确切地说,我有例如:
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。
请帮助。
答案 0 :(得分:1)
您不能使用正则表达式来解析HTML(请参阅this)。相反,您可以像这样使用原生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"));
&#13;
另一种方法:(更好的方法)
您可以将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"));
&#13;
注意:选择器可以是任何内容(任何有效的CSS Selector)。这更灵活。