strcase/snake.go

33 lines
725 B
Go
Raw Normal View History

2015-10-09 17:13:05 +08:00
// Package strcase converts strings to snake_case or CamelCase
package strcase
import (
"strings"
)
// Converts a string to snake_case
func ToSnake(s string) string {
2017-11-29 08:52:26 +08:00
s = addWordBoundariesToNumbers(s)
2015-10-09 17:13:05 +08:00
s = strings.Trim(s, " ")
n := ""
for i, v := range s {
// treat acronyms as words, eg for JSONData -> JSON is a whole word
preIsCapital := false
2018-04-27 15:43:56 +08:00
if i > 0 {
w := s[i-1]
preIsCapital = w >= 'A' && w <= 'Z'
}
if i > 0 && v >= 'A' && v <= 'Z' && n[len(n)-1] != '_' && !preIsCapital {
// add underscore if next letter is a capital
2015-10-09 17:13:05 +08:00
n += "_" + string(v)
} else if v == ' ' {
// replace spaces with underscores
2015-10-09 17:13:05 +08:00
n += "_"
} else {
n = n + string(v)
}
}
n = strings.ToLower(n)
return n
}