8

[Golang] kebab-case to camelCase

 3 years ago
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.
neoserver,ios ssh client

[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.

Run Code on Go Playground

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:


References:

[2]Naming convention (programming) - Wikipedia


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK