Search code examples
kubernetes-helmgo-templates

go template split string by the second to last character


I am trying to split a string only by the second to last character, for example: Having this string xxx-xxx-xxx-xxx-xxx I would like to get only this xxx-xxx-xxx and remove the last part after the third "-" or the second last "-", the string will always have 4 "-" and character or numbers in between.

At the moment I have something like this {{ splitList "-" .Values.global.stackName | list ._0 ._1 ._2 | join "-" | quote }} Does not work because I dont know how to pipe the array from the first split int the second one and join them again.


Solution

  • You may use the slice function to get only the first 3 elements of the splitted list:

    {{ slice (splitList "-" .Values.global.stackName) 0 3 | join "-" | quote }}
    

    Also note that if your input is guaranteed to be of fixed format (that is, 3 characters then - then 3 chars again then - then 3 chars again before -), you may use printf with the proper format string to keep only the first (at most) 11 characters:

    {{ printf "%.11s" .Values.global.stackName | quote }}
    

    If the input only contains ASCII characters (no multi-byte unicode characters), you may also slice the input string to retain only the first 11 characters (bytes):

    {{ slice .Values.global.stackName 0 11 | quote }}