Skip to content

Commit 329b601

Browse files
authored
fix(caser): ToSnake does not replace spaces with _ (#1148)
#### Summary Fixes #728 Another approach to #1094. Instead of regular expressions we use `strings.Fields` to get rid of the spaces and replace them with `_`. Then we use `_` as a word separator.
1 parent 6d3f752 commit 329b601

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

caser/caser.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,10 +78,13 @@ func (c *Caser) ToSnake(s string) string {
7878
var result string
7979
var words []string
8080
var lastPos int
81+
82+
s = strings.Join(strings.Fields(s), "_")
83+
8184
rs := []rune(s)
8285

8386
for i := 0; i < len(rs); i++ {
84-
if i > 0 && unicode.IsUpper(rs[i]) {
87+
if i > 0 && (unicode.IsUpper(rs[i]) || rs[i] == '_') {
8588
// check if next word is initialism
8689
if initialism := c.startsWithInitialism(s[lastPos:]); initialism != "" {
8790
words = append(words, initialism)
@@ -100,6 +103,9 @@ func (c *Caser) ToSnake(s string) string {
100103
}
101104

102105
words = append(words, s[lastPos:i])
106+
if rs[i] == '_' {
107+
i++
108+
}
103109
lastPos = i
104110
}
105111
}

caser/caser_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,17 @@ func Test_ToSnake(t *testing.T) {
3131
{Camel: "IAMRoles", Snake: "iam_roles"},
3232
{Camel: "testIAM", Snake: "test_iam"},
3333
{Camel: "TestAWSMode", Snake: "test_aws_mode"},
34+
{Camel: "Hello World", Snake: "hello_world"},
35+
{Camel: "Hello Wor ld", Snake: "hello_wor_ld"},
36+
{Camel: "Hello Wor Ld", Snake: "hello_wor_ld"},
37+
{Camel: "Hello wor ld", Snake: "hello_wor_ld"},
38+
{Camel: "Hello wOr ld", Snake: "hello_w_or_ld"},
39+
{Camel: "Hello wOrOr ld", Snake: "hello_w_or_or_ld"},
40+
{Camel: "H e l l o", Snake: "h_e_l_l_o"},
41+
{Camel: "H e l l o ", Snake: "h_e_l_l_o"},
42+
{Camel: " H e l l o", Snake: "h_e_l_l_o"},
43+
{Camel: " H e l l o ", Snake: "h_e_l_l_o"},
44+
{Camel: "Hello World", Snake: "hello_world"},
3445
}
3546
t.Parallel()
3647
c := New()

0 commit comments

Comments
 (0)