Using a modified version of this in 2021 (Hugo has built in functions which do most of the work)
{{ $headers := findRE "<h[2].*?>(.|\n])+?</h[2]>" .Content }}
{{ if and (ge (len $headers) 1) (ne $.Params.toc "none") }}
<ul class="menu-list">
{{ range $headers }}
{{ $header := . | plainify | htmlUnescape }}
<li><a href='#{{ $header | anchorize }}'>{{ $header }}</a></li>
{{ end }}
</ul>
{{ end }}
Read full topic