Taking a video title and turning it into a URL

Hi!

I’m working with Hugo and have a use case where there are a lot of various video titles that all follow roughly the same considerations:

  • remove all underscores and replace with dashes
  • remove all dashes with spaces on either side and replace with a dash with no spaces
  • remove all special characters (? and !) and replace with nothing
  • remove all periods and replace with dashes
  • remove all remaining spaces and replace with dashes
  • everything lowercase

So far I have the following code written out, and I’m trying to figure out how to streamline it.

                          {{ $step1_title := replace .title "_" " " }}
                          {{ $step2_title := replace $step1_title " - " "-" }}
                          {{ $step3_title := replace $step2_title "?" "" }}
                          {{ $step4_title := replace $step3_title "." "-" }}
                          {{ $step5_title := replace $step4_title " " "-" | lower }}
                          {{ $step5_title }}

It seems like a lot of steps, and doesn’t account for both ? and !. I’m assuming replaceRE would be more appropriate for that step, yet it won’t recognize those characters when defined with [?]|[!]. Any pointers for making the above more efficient would be much appreciated.

Do you know the function urlize? This might be what you want to achieve?

1 Like