How to trim and truncate a URL?

If you have a URL (external to your site) such as how can you trim the “http://www” part and truncate the result, so you get something like

Btw the trimming needs to work for either “http” or “https”.

This is the end result I’m looking for:

<a href="{{.}}" target="_blank"></a>

The following only works for “http” and I couldn’t find a truncation function in the Hugo docs.

<a href="{{.}}" target="_blank">{{trim . "http://www-"}}</a>

UPDATE: I just tried doing something like this:

{{trim . "http://www.-" | slicestr 0 20}}

but I get an error “error calling slicestr: start argument must be integer”. Not sure how to pipe the trim result to slicestr without getting this error.

Wrap your first argument to slicestr in some parens.

Hmm that doesn’t seem to work.

{{trim . "https://www.-" | slicestr (0 5)}}

at <0>: can't give argument to non-function 0

I’ve tried:

`{{(trim . "https://www.-") | slicestr 0 5}}`
`{{trim . "https://www.-" | slicestr (0) 5}}`
`{{trim . "https://www.-" | (slicestr 0 5)}}`

You took my post a little bit too literal …

{{  slicestr (trim . "http://www.-") 0 20}}

Go Template Trivia

In a Go template pipeline, the previous result is passed as the last argument to the next command, so you’re asking the template to execute:

slicestr 0 20 ""

That’s why the pipe isn’t working as you’d expect.

Ah that works. Thanks.

As moorereason pointed out the output is passed as the last argument. Is there any way I can trim http://www. OR https://www. as I can’t chain them link this

{{ slicestr (trim . "http://www.-" | trim "https://www.-") 0 20 }}

Ok I’d have to do this ugly thing:

{{substr (trim (trim . "https://www.-") "http://www.-") 0 20}}

UPDATE: FInally to get the “…” to show that it’s truncated I’d need this:

<a href="">{{substr (trim (trim . "https://www.-") "http://www.-") 0 17}}...</a>

I wish there were cleaner and more intuitive ways of doing small things like this.

Hugo is a static site generator, and the template logic is (and should be) limited.

The clean way of doing what you do is to separate the link text and the link URL into two separate fields; then there is no need for this string magic.

It would be cleaner if something like this existed:

{{ replaceRE `^https?://www\.(.{0,17}).*` `$1` .URL }}
func ReplaceRE(pattern, repl, src string) string

Nothing magical about it…unless regexp is new to you, then it does look like magic. :smile:

I can work on adding such a func to the funcMap if we like the idea. I vote :+1:

1 Like

I like :+1:

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.