Home > Enterprise >  How to convert a string to camelCase in Go?
How to convert a string to camelCase in Go?

Time:11-24

What is the simplest way to convert a string with spaces to a single camelCased string?

For example: "This is a string with spaces" -> "thisIsAStringWithSpaces"

CodePudding user response:

Can avoid regex if only dealing with spaces. See strings package for useful helpers that can be used to expand this functionality:

str := "This is a string with spaces"
words := strings.Split(str, " ")
key := strings.ToLower(words[0])
for _, word := range words[1:] {
    key  = strings.Title(word)
}
log.Println(key)

CodePudding user response:

Personally, I like to use this library https://github.com/iancoleman/strcase

strcase.ToLowerCamel("This is a string with spaces")
  •  Tags:  
  • go
  • Related