Parsing string URLs

Good day everyone!

I’m looking at creating a shortcode that will create an img + photo credit. Something like this:
{{< img-credit “” >}}

would produce something like this:

Photo credit:

Now, that would require parsing of URL string and use the hostname portion. I’ve found the go language has a struct named url that we can use:

I’d see something like:
{{ $u, $err := url.Parse(“”) }}
{{ $u.Host }}

My question is, can we use go functions like this one inside a shortcode / template? If not, what solution would you use?


No you cannot. You may be able to do it with the builtin string template funcs. Not sure.

Check out the replaceRE template function.

1 Like

@sleclerc That image is coming up as a broken link. Can you write out your desired result, please?

It did work! Thanks a lot :slight_smile:

I just changed the original message. Thanks for pointing it!

Try this code snippet:

{{ $url := "" }}
{{ $url := replace $url "https://" "" }}
{{ $url := replace $url "http://" "" }}
{{ $url := split $url "/" }}

{{ if ge (len $url) 1 }}
    {{ index $url 0 }}
{{ end }}

It outputs However, it doesn’t remove port numbers like in this url:

But this case should be rare.


Thanks ! I’ll test both solutions.