Table of contents regex issue

I have created a custom table of contents partial that shows a TOC if there are 2 or more <h2> headings:

{{ $headings := findRE "<h2.*?>(.|\n])+?</h2>" .Content }}
{{ if ge (len $headings) 2 }}
  <nav class="toc" aria-labelledby="toc-heading">
    <h2 id="toc-heading">Table of contents</h2>
      {{ range $headings }}
          <a href="#{{ . | htmlUnescape | plainify | urlize }}">
            {{ . | htmlUnescape | plainify }}
      {{ end }}
{{ end }}

However, my pages sometimes include <h2> elements inside Shadow DOM elements that I don’t want to include in the TOC. These elements have the class .demo. I’m wondering how I can either

  • Only match <h2>s in the regex at the the top of the template where the parent is not class="demo"
  • Or remove these elements from the final list of <h2>s once it has been compiled

Thanks (and sorry for the regex)

1 Like

if header id with dash -, use below code.

<a href="#{{ replace (. | htmlUnescape | plainify) " " "-" }}

1 Like