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 {
|
2018-03-11 15:56:25 +08:00
|
|
|
// treat acronyms as words, eg for JSONData -> JSON is a whole word
|
|
|
|
nextIsCapital := false
|
|
|
|
if i + 1 < len(s) {
|
|
|
|
w := s[i+1]
|
|
|
|
nextIsCapital = w >= 'A' && w <= 'Z'
|
|
|
|
}
|
|
|
|
if i > 0 && v >= 'A' && v <= 'Z' && n[len(n)-1] != '_' && !nextIsCapital {
|
|
|
|
// add underscore if next letter is a capital
|
2015-10-09 17:13:05 +08:00
|
|
|
n += "_" + string(v)
|
|
|
|
} else if v == ' ' {
|
2018-03-11 15:56:25 +08:00
|
|
|
// replace spaces with underscores
|
2015-10-09 17:13:05 +08:00
|
|
|
n += "_"
|
|
|
|
} else {
|
|
|
|
n = n + string(v)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
n = strings.ToLower(n)
|
|
|
|
return n
|
|
|
|
}
|