Skip to content

Commit d37606d

Browse files
jmooringbep
authored andcommitted
tpl/strings: Add TrimSpace function
Closes #12962
1 parent f5e54d9 commit d37606d

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

tpl/strings/strings.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,17 @@ func (ns *Namespace) Trim(s, cutset any) (string, error) {
450450
return strings.Trim(ss, sc), nil
451451
}
452452

453+
// TrimSpace returns the given string, removing leading and trailing whitespace
454+
// as defined by Unicode.
455+
func (ns *Namespace) TrimSpace(s any) (string, error) {
456+
ss, err := cast.ToStringE(s)
457+
if err != nil {
458+
return "", err
459+
}
460+
461+
return strings.TrimSpace(ss), nil
462+
}
463+
453464
// TrimLeft returns a slice of the string s with all leading characters
454465
// contained in cutset removed.
455466
func (ns *Namespace) TrimLeft(cutset, s any) (string, error) {

tpl/strings/strings_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -854,3 +854,30 @@ func TestDiff(t *testing.T) {
854854

855855
}
856856
}
857+
858+
func TestTrimSpace(t *testing.T) {
859+
t.Parallel()
860+
c := qt.New(t)
861+
862+
for _, test := range []struct {
863+
s any
864+
expect any
865+
}{
866+
{"\n\r test \n\r", "test"},
867+
{template.HTML("\n\r test \n\r"), "test"},
868+
{[]byte("\n\r test \n\r"), "test"},
869+
// errors
870+
{tstNoStringer{}, false},
871+
} {
872+
873+
result, err := ns.TrimSpace(test.s)
874+
875+
if b, ok := test.expect.(bool); ok && !b {
876+
c.Assert(err, qt.Not(qt.IsNil))
877+
continue
878+
}
879+
880+
c.Assert(err, qt.IsNil)
881+
c.Assert(result, qt.Equals, test.expect)
882+
}
883+
}

0 commit comments

Comments
 (0)