【问题标题】:How to find out pairs of opening and closing html tags using javascript?如何使用javascript找出成对的打开和关闭html标签?
【发布时间】:2020-10-24 14:00:55
【问题描述】:

如何在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('&lt;/')... 但这仍然不能保证这样的开头和结尾对:

<div> ---> opening

</div> --->  closing

[pair]

注意

这是为了找到标签的嵌套,以便我可以同样缩进 html && 将它们中的每一个显示为块。我不想使用 parse5、marked、prismjs 或 highlight js 之类的包。

我的要求是定制的。 -> (只是为了找到开始和结束标记对,这样我就可以从上面解析的 html 数组中找到东西是如何嵌套的)

【问题讨论】:

  • 像可视化代码一样使用 ide
  • 没有。这是针对 html 网页的……不能在 vs 代码上完成……(我们为此目的有扩展……对)……这是为了在网页中以特定方式解析和显示 html……

标签: javascript


【解决方案1】:

这就是我的方法:

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-16
    • 2019-06-18
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多