-
Notifications
You must be signed in to change notification settings - Fork 181
/
format.go
119 lines (99 loc) · 2.28 KB
/
format.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package strutil
import (
"regexp"
"strings"
)
// Some alias methods.
var (
Lower = strings.ToLower
Upper = strings.ToUpper
Title = strings.ToTitle
)
/*************************************************************
* change string case
*************************************************************/
// Lowercase alias of the strings.ToLower()
func Lowercase(s string) string {
return strings.ToLower(s)
}
// Uppercase alias of the strings.ToUpper()
func Uppercase(s string) string {
return strings.ToUpper(s)
}
// UpperWord Change the first character of each word to uppercase
func UpperWord(s string) string {
if len(s) == 0 {
return s
}
ss := strings.Split(s, " ")
ns := make([]string, len(ss))
for i, word := range ss {
ns[i] = UpperFirst(word)
}
return strings.Join(ns, " ")
}
// LowerFirst lower first char
func LowerFirst(s string) string {
if len(s) == 0 {
return s
}
f := s[0]
if f >= 'A' && f <= 'Z' {
return strings.ToLower(string(f)) + s[1:]
}
return s
}
// UpperFirst upper first char
func UpperFirst(s string) string {
if len(s) == 0 {
return s
}
f := s[0]
if f >= 'a' && f <= 'z' {
return strings.ToUpper(string(f)) + s[1:]
}
return s
}
// Snake alias of the SnakeCase
func Snake(s string, sep ...string) string {
return SnakeCase(s, sep...)
}
// SnakeCase convert. eg "RangePrice" -> "range_price"
func SnakeCase(s string, sep ...string) string {
sepChar := "_"
if len(sep) > 0 {
sepChar = sep[0]
}
newStr := toSnakeReg.ReplaceAllStringFunc(s, func(s string) string {
return sepChar + LowerFirst(s)
})
return strings.TrimLeft(newStr, sepChar)
}
// Camel alias of the CamelCase
func Camel(s string, sep ...string) string {
return CamelCase(s, sep...)
}
// CamelCase convert string to camel case.
// Support:
// "range_price" -> "rangePrice"
// "range price" -> "rangePrice"
// "range-price" -> "rangePrice"
func CamelCase(s string, sep ...string) string {
sepChar := "_"
if len(sep) > 0 {
sepChar = sep[0]
}
// Not contains sep char
if !strings.Contains(s, sepChar) {
return s
}
// Get regexp instance
rgx, ok := toCamelRegs[sepChar]
if !ok {
rgx = regexp.MustCompile(regexp.QuoteMeta(sepChar) + "+[a-zA-Z]")
}
return rgx.ReplaceAllStringFunc(s, func(s string) string {
s = strings.TrimLeft(s, sepChar)
return UpperFirst(s)
})
}