Regex that matches all div tags

Viewed 57

I need a regex expression that matches all div tags in the HTML code whithout using a DOM parser

I've tryed this

var expression = /<div\s*"?.*"?\s*>[\S\s]*?<\/div>/gi;
var regexpress = new RegExp(expression)

matches = text.match(regexpress);
if (matches != null) { returnarray.push(matches); }
return returnarray;

But the result:

input text:
<div wdlm></div>
<div></div>
<div></div>

output array:
element 1:<div wdlm></div> <div></div>
element 2:<div></div>

It takes 2 divs at the same time for the 1st element of the array.


By reading comments this is the solution

        var returnarray = [];
        var matches = null;
        var expression = /<div\s*"?.*?"?\s*>[\S\s]*?<\/div>/gi;       
        var regexpress = new RegExp(expression);
        
        matches = text.match(regexpress);
        if(matches != null) {
            returnarray.push(matches);
        }
        
        return returnarray;

Also, I'm flipping my brain over a question:

Can the regex be allocated dynamically?

Something like

var expression = /<VARIABLE\s*"?.*"?\s*>[\S\s]*?<\/VARIABLE>/gi;

Where VARIABLE it's a var VARIABLE, taking every element in the code by changing the input of VARIABLE and not only div?


Could someone help me with this, please?

1 Answers

I don't recommend using regex to parse an HTML string. If you can live with the limitation, here is a regex solution for arbitrary HTML tags that does not support nesting, and fails with corner cases, such as <div title="</div>"></div>:

const input = '<div wdlm></div>\n' +
  '<div></div>\n' +
  '<div></div>';

function parseTags(tag, str) {
  let re = new RegExp('<' + tag + '\\b\\s*"?.*?"?\\s*>[\\S\\s]*?<\\/' + tag + '>', 'gi');
  return str.match(re) || [];
}

let tags = parseTags('div', input);
console.log('- input: "' + input + '"\n- tags: ' + JSON.stringify(tags, null, ' '));

Output:

- input: "<div wdlm></div>
<div></div>
<div></div>"
- tags: [
 "<div wdlm></div>",
 "<div></div>",
 "<div></div>"
]
Related