const htmlStr = `
<div>
<div>
<span>123</span>
<a>222</a>
<div>
<button>333</button>
<br/>
</div>
</div>
</div>
`;
function getHtmlTreeDepth(htmlStr) {
let depth = 0;
let maxDepth = 0;
const stack = [];
const tagRegex = /<\/?([a-z][a-z0-9]*)[^>]*>/gi;
htmlStr.replace(tagRegex, (tag) => {
console.log(tag)
if (tag.startsWith('</')) {
// 闭合标签
depth--;
stack.pop();
} else if (!tag.endsWith('/>')) {
// 非自闭合的开放标签
depth++;
maxDepth = Math.max(maxDepth, depth);
stack.push(tag.match(/<([a-z]+)/i)[1]);
}
// 自闭合标签(如 <br/>)不改变深度
return tag;
});
return maxDepth;
}
const depth = getHtmlTreeDepth(htmlStr);
console.log(depth); // 输出: 4
console