

[Golang] kebab-case to camelCase
source link: http://siongui.github.io/2017/02/18/go-kebab-case-to-camel-case/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[Golang] kebab-case to camelCase
February 18, 2017
Convert the kebab-case (also called spinal-case, Train-Case, or Lisp-case) [4] string to camelCase [3] in Golang.
The motivation is to convert the property name of CSS (kebab-case) to element's inline style attribute (camelCase) manipulated by JavaScript.
converter.go | repository | view raw
package converter import "strings" func kebabToCamelCase(kebab string) (camelCase string) { isToUpper := false for _, runeValue := range kebab { if isToUpper { camelCase += strings.ToUpper(string(runeValue)) isToUpper = false } else { if runeValue == '-' { isToUpper = true } else { camelCase += string(runeValue) } } } return }
Use range keyword [5] to iterate over the string. If - is met, isToUpper is set to true. In next iteration convert the letter to upper case by strings.ToUpper, and set isToUpper as false.
converter_test.go | repository | view raw
package converter import ( "testing" ) func TestKebabCaseToCamelCase(t *testing.T) { kebabString := "border-left-color" t.Log(kebabString) camel := kebabToCamelCase(kebabString) if camel != "borderLeftColor" { t.Error(camel) return } t.Log(camel) }
Tested on:
- Ubuntu Linux 16.10, Go 1.8
- The Go Playground
References:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK