javascript – Regex that matches all div tags
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?
Read more here: Source link