Skip to content

Commit

Permalink
feat: add new ChopEnd and ChopStart string helpers (#591)
Browse files Browse the repository at this point in the history
* feat: add new laravel string helpers ChopStart and ChopEnd - merge with master

* break on first match instead of return

* reorder methods to their alphabetical position

* reorder test methods to their alphabetical position
  • Loading branch information
shayan-yousefi authored Aug 9, 2024
1 parent e303e5b commit 1814e7f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
26 changes: 26 additions & 0 deletions support/str/str.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,32 @@ func (s *String) CharAt(index int) string {
return Substr(s.value, index, 1)
}

// ChopEnd remove the given string(s) if it exists at the end of the haystack.
func (s *String) ChopEnd(needle string, more ...string) *String {
more = append([]string{needle}, more...)

for _, v := range more {
if s.EndsWith(v) {
s.value = strings.TrimRight(s.value, v)
break
}
}
return s
}

// ChopStart remove the given string(s) if it exists at the start of the haystack.
func (s *String) ChopStart(needle string, more ...string) *String {
more = append([]string{needle}, more...)

for _, v := range more {
if s.StartsWith(v) {
s.value = strings.TrimLeft(s.value, v)
break
}
}
return s
}

// Contains returns true if the string contains the given value or any of the values.
func (s *String) Contains(values ...string) bool {
for _, value := range values {
Expand Down
16 changes: 16 additions & 0 deletions support/str/str_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,22 @@ func (s *StringTestSuite) TestCharAt() {
s.Equal("", Of("こんにちは、世界!").CharAt(-200))
}

func (s *StringTestSuite) TestChopEnd() {
s.Equal("Goravel", Of("GoravelFramework").ChopEnd("Framework").String())
s.Equal("https://goravel", Of("https://goravel.dev").ChopEnd(".dev").String())
s.Equal("https://goravel", Of("https://goravel.dev").ChopEnd(".dev", ".com").String())
s.Equal("https://goravel", Of("https://goravel.com").ChopEnd(".dev", ".com").String())
s.Equal("go", Of("golaravel").ChopEnd("laravel").String())
}

func (s *StringTestSuite) TestChopStart() {
s.Equal("Framework", Of("GoravelFramework").ChopStart("Goravel").String())
s.Equal("goravel.dev", Of("https://goravel.dev").ChopStart("https://").String())
s.Equal("goravel.dev", Of("https://goravel.dev").ChopStart("https://", "http://").String())
s.Equal("goravel.dev", Of("http://goravel.dev").ChopStart("https://", "http://").String())
s.Equal("goravel", "go"+Of("laravel").ChopStart("la").String())
}

func (s *StringTestSuite) TestContains() {
s.True(Of("kkumar").Contains("uma"))
s.True(Of("kkumar").Contains("kumar"))
Expand Down

0 comments on commit 1814e7f

Please sign in to comment.