Adding to the code from your previous related topic, replace .Content in your template with:
{{ if gt ((findRE `(?i)<h2` .Content) | len) 1 }}
{{ replaceRE `(?s)(.*?)(<h2.*)` (print "$1" .TableOfContents "$2") .Content | safeHTML }}
{{ else }}
{{ .Content }}
{{ end }}
Example:
git clone --single-branch -b hugo-forum-topic-42666 https://github.com/jmooring/hugo-testing hugo-forum-topic-42666
cd hugo-forum-topic-42666
hugo server