如何使用javascript找到打开和关闭html标记对?

如何使用javascript找到打开和关闭html标记对?,javascript,Javascript,如何在javascript中找到打开和关闭html标记对 因此,我有一个经过解析的html数组: /// this is just markup only : any inner text is omitted for simplicity. const parsedHtml = [ '<div class="container">', '<div class="wrapper">', '<h3&g

如何在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)
///这只是标记而已:为了简单起见,省略了任何内部文本。
const parsedHtml=[
'',
'',
'',
'',
“”,
“

”, '', '', '', '', '', '' ] //整个数组是一块html代码(嵌套按上述顺序排列)
这里的想法是找到开始和结束标记对

(只有索引。)

这样我就可以分离出代码块。。。像这样:

<div class="container">
...
</div>


// or

<h3>
</h3>

//or 

<span>
...
</span>


<div> ---> opening

</div> --->  closing

[pair]


...
//或
//或
...
只需要一种方法来查找与开始标记匹配的结束标记的索引。 (将其视为vscode中打开的代码块)

我本可以检查一下parsedHtml[I].startsWith('(只是为了找到开始和结束标记对,这样我就可以从上面解析的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;
}
var parsedHtml=[
'',
'',
'',
'',
“”,
“

”, '', '', '', '', '', '' ]; var getTag=(s)=>s.replace(//gi',).split('')[0]; var isCloseTag=(t)=>t.includes('/'); var index=parsedHtml.map(getTag.reduce)(collectIndexes,{}); console.log(JSON.stringify(index));//{“div”:[[0,11],[1,10],“h3”:[[2,3],“p”:[[4,5],“span”:[[6,9],“a”:[[7],“img”:[[8]} 函数集合索引(索引、标记、i){ 常量标记名=tag.replace('/',''); if(!(索引中的标记名)){ 索引[标记名]=[[i]]; 回报指数; } 如果(isCloseTag(tag)){ 索引[标记名].reverse().find((ins)=>ins.length==1.push(i); 回报指数; } 索引[tagName].push([i]); 回报指数; }
像visual codeNo一样使用ide。这是一个html网页…不能在vs代码上完成…(我们有用于此目的的扩展…对)…这是用于在网页内以特定方式解析和显示html。。