[Golang] kebab-case to camelCase


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.

Run Code on Go Playground

converter.go | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
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:


References:

[1]
[2]Naming convention (programming) - Wikipedia
[3]Camel case - Wikipedia
[4]
[5][Golang] Iterate Over UTF-8 Strings (non-ASCII strings)