簡體   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