replaceRE on page template against links with spaces

I’m trying to replace all my pages’ links’ spaces with hyphens. I put this at the end of single.html:

{{replaceRE `(a href=.+)%20(\w+)` “$1-$2” .Content}}

The problem is that nothing is being changed!

What am I doing wrong? Thanks!

First, are you sure that your pages contain HTML links rather than markdown ones? Then, i guess your RE might not work as you want it to. Did you try it out on or something similar?

Yes, they are HTML links. And I did use regex101. Ok now it’s just displaying “$1-$2”.

{{ replaceRE .Content `(a href=.+)%20(\w+)` “$1-$2” }}

figured it out.
{{$content := replaceRE `(a href=.+)%20(\w+)` `$1-$2` .Content}}

{{ $content | safeHTML }}

What happens with more than one space in the link?

1 Like

Oh yeah I’ll refine the regex, the problem was concerning the hugo replaceRE syntax, which wasn’t working at all until now. The doc examples don’t seem to be correct… the only way that worked for me is replaceRE PATTERN REPLACEMENT INPUT, with PATTERN and REPLACEMENT both between backticks, and then all piped to safeHTML. I’ll edit the solution with improved regex in a bit

{{$content := replaceRE `a href="\.\.\/(.+%20.+)+"` `$1` .Content}}
(all my links happen to be in the form a href="…/url", hence the \.\.\/ in the regex)
{{$content = replace $content "%20" "-"}}
{{ $content | safeHTML }}

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.