Is there a function to split a string into a slice?

I want to split a string into a slice based on a delimiter or set of delimiters. Is there a way to do this? I’ve looked in the docs and tried out some things and nothing seems to do this, even functions with names that seem appropriate. I’m looking at you split and slicestr

And how to go back from a slice to a string using a certain delimiter?

Even better would be a way to check if any element in a slice exists in a string. I want to then replace that match in the string with something else.

Can’t do this with regex (wish I could) because the components of the pattern are in the slice array and there are MANY elements. … but now that I’m thinking about it, maybe I could could append all the elements of the slice with some regex sugar in between them, make a huge long string literal, save it as a variable, and use that variable as the pattern to match.

So many ways to think of doing this but none of them really available. I feel like a function that would split a string into a slice would be a common or useful function.

To clarify, by delimiter do you mean another string, rather than a single character?

well whatever… " " or "," or "'" or sure, could be some other string as needed.

I actually just tried split again and I may have misjudged it. It looks like it does turn into a slice. How would i check the data type of a variable?

1 Like

Nevermind, figured that out too. reflect.isSlice will check that.

And delimit will turn a slice into a string

and compliment will filter out elements that are in one slice and another, but leave elements that are in the first slice but not the second.

1 Like

@gaetawoo - a sample using the functions you mentioned, if it helps:

<!-- init a string -->
{{ $the_string := "gaetawoo" }}

<!-- split it on empty string, creating a slice of characters -->
{{ $the_slice := split $the_string "" }}

<!-- shuffle the slice -->
{{ $the_shuffled_slice := shuffle $the_slice }}

<!-- convert the slice back into a string by joining each character on empty string -->
{{ $the_shuffled_string := delimit $the_shuffled_slice "" }}

<!-- output it -->
{{ $the_shuffled_string }}

<!-- it outputs "atgwooea", which will change every time you run hugo -->

Thank you, it is helpful.

I’ll update the docs for clarification that split creates a slice.

1 Like

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