Deleting all anchor elements from content

This is a bit of an odd problem, but how would I go about removing all <a> tags generated from a markdown file in a single.html template? Use case: <a> tags are apparently not valid for certain Google structured data.

Doing {{.Content}} generates the following:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>

<p><a class="post" href="https://example.com/" title="Link">This is a Link</a></p>
<p><a class="post2" href="https://google.com/" title="Link2">This is a second Link</a></p>

How would I go about deleting every instance of the <a> tag, so removing

<a class="post" href="https://example.com/" title="Link"> and </a>
<a class="post2" href="https://example.com/" title="Link2"> and </a>

I’d like to keep the text: This is a Link and This is a second Link

Each link may have a unique class, href and title. Some links may be mailto links.

You could use replaceRE for this. You’ll wanna tweak this to your needs (and make the match more specific) but something like this would work.

{{ $content := replaceRE "<a .*\">" "" .Content }}
{{ $content = replaceRE "</a>" "" $content }}
{{ $content | safeHTML }}
2 Likes