如何在javascript中找到打开和关闭html标记对?
所以我有一个经过解析的html:数组
/// this is just markup only : any inner text is omitted for simplicity.
const parsedHtml = [
'<div class="container">',
'<div class="wrapper">',
'<h3>',
'</h3>',
'<p>',
'</p>',
'<span>',
'<a href="#">',
'<img src="./img.svg">',
'</span>',
'</div>',
'</div>'
]
// this whole array is a block of html code (nesting is in the above order)
所以这里的想法是找到开始和结束标签对;
(只是索引。(
这样我就可以分离出代码块。。。像这样:
<div class="container">
...
</div>
// or
<h3>
</h3>
//or
<span>
...
</span>
只需要一种方法来找到与开始标记匹配的结束标记的索引。(将其视为打开vscode中的代码块(
我本可以检查一下parsedHtml[i].startsWith('</')
。。。但这仍然不能保证像这样的打开和关闭对:
<div> ---> opening
</div> ---> closing
[pair]
注意
这是为了找到标签的嵌套,这样我就可以像缩进html一样&;将它们分别显示为块。我不想使用parse5、markd、prismjs或highlight-js之类的包。
我的要求是定制的->(只是为了找到开始和结束标签对,这样我就可以从上面解析的html数组中找到东西是如何嵌套的(
这是我的方法:
var parsedHtml = [
'<div class="container">',
'<div class="wrapper">',
'<h3>',
'</h3>',
'<p>',
'</p>',
'<span>',
'<a href="#">',
'<img src="./img.svg">',
'</span>',
'</div>',
'</div>'
];
var getTag = (s) => s.replace(/<|>/gi, '').split(' ')[0];
var isCloseTag = (t) => t.includes('/');
var indices = parsedHtml.map(getTag).reduce(collectIndices, {});
console.log(JSON.stringify(indices)); // {"div":[[0,11],[1,10]],"h3":[[2,3]],"p":[[4,5]],"span":[[6,9]],"a":[[7]],"img":[[8]]}
function collectIndices(indices, tag, i) {
const tagName = tag.replace('/', '');
if (!(tagName in indices)) {
indices[tagName] = [[i]];
return indices;
}
if (isCloseTag(tag)) {
indices[tagName].reverse().find((ins) => ins.length === 1).push(i);
return indices;
}
indices[tagName].push([i]);
return indices;
}
我在这里使用js-regex找到了这个答案:https://www.octoparse.com/blog/using-regular-expression-to-match-html
你所要做的就是把你要找的标签放进去。
如果我在找标签:/<as*.*>s*.*</a>/gi
您可以使用此regex工具进行测试:https://regexr.com/