繁体   English   中英

如何使用 javascript 找出成对的打开和关闭 html 标签?

[英]How to find out pairs of opening and closing html tags using 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>',
    '</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、marked、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 正则表达式找到了这个答案: https://www.octoparse.com/blog/using-regular-expression-to-match-html

您所要做的就是将标签放入您正在寻找的地方。

如果我正在寻找 a 标签:/<a\s*.*>\s*.*<\/a>/ /<a\s*.*>\s*.*<\/a>/gi

您可以使用此正则表达式工具对其进行测试: https://regexr.com/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM