Denis Denis - 1 year ago 75
TypeScript Question

JavaScript Regex to match DIVs with specific class

I am trying to match a RegEx for a string with HTML tags. More precisely, i have for example:

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>']


I want to filter this string divs by class "wrapper" using RegEx on my Angular2 project. I'm not using jQuery.

Any help please.

Answer Source

You can not use regular expression to parse HTML (see this). Instead, you can use the native DOMParser like this:

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

Another approach: (the better one)

You can append the html to a div and then select only the matches elements inside that 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"));

Note: The selector could be anything (any valid CSS Selector). This is more flexible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download