Simpler way to cut this string?

In my config.yaml I have the following:

  Business: Joe's Plumbing
  number: 9108647038

Now I want the following html output:

<a href="tel:+19108647038">(910) 864 - 7038</a>

Currently I have this in my template:

{{ $phone := site.Params.number }}
{{ $phone1 := substr $phone 0 3 }}
{{ $phone2 := substr $phone 3 3 }}
{{ $phone3 := substr $phone 6 4 }}

<a href="tel:+1{{ $phone }}">({{ $phone1 }}) {{ $phone2 }} - {{ $phone3 }}</a>

Is there an easier way to accomplish this?

EDIT to say: my code technically outputs exactly what I want, but it isn’t exactly DRY, I feel. And it’s ugly. And there has to be a more efficient way to encode/decode phone numbers?

I dunno.

Not urgent. Just checking.

<a href="tel:+1{{ site.Params.number }}">{{ replaceRE `(\d{3})(\d{3})(\d{4})` "($1) $2-$3" site.Params.number }}</a>

one day I should actually learn Go so I can stop bothering you, @jmooring :joy:

Thanks for being so cool.

1 Like

Check out replaceRE documentation. This is more about knowing the available Hugo templating functions than knowing the Go language.

When I see requests like this one, I have the feeling one should take a step back to see what exactly they want :wink: It is probably better to format the number the way you want to display it (+ in your configuration and just live with the extra characters in there for the href-attribute. The <a href="tel:+12(123)12.12"> is an allowed format for the telephone number. This format even has a feature where you add a p and the phone using the link will wait 1s before adding numbers after the p. <a href="tel:+12(123)45.67p999"> is allowed. Most browsers will understand various formatting options and will remain to be able to understand weird formats too. so there is no reason to “normalise” the numbers for the href-attribute…

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