diff options
author | Joe Mooring <[email protected]> | 2024-10-19 11:13:20 -0700 |
---|---|---|
committer | Bjørn Erik Pedersen <[email protected]> | 2024-10-19 21:10:00 +0200 |
commit | d37606d2c2174e20cfba5150812da83378078f09 (patch) | |
tree | c7ec021631cb3d7f469b7ba5ae64ae94b2d6400f | |
parent | f5e54d9c7d6642ba5435e7342761f684c84f4b1a (diff) | |
download | hugo-d37606d2c2174e20cfba5150812da83378078f09.tar.gz hugo-d37606d2c2174e20cfba5150812da83378078f09.zip |
tpl/strings: Add TrimSpace function
Closes #12962
-rw-r--r-- | tpl/strings/strings.go | 11 | ||||
-rw-r--r-- | tpl/strings/strings_test.go | 27 |
2 files changed, 38 insertions, 0 deletions
diff --git a/tpl/strings/strings.go b/tpl/strings/strings.go index 02f9a2b1e..eb5aee3cb 100644 --- a/tpl/strings/strings.go +++ b/tpl/strings/strings.go @@ -450,6 +450,17 @@ func (ns *Namespace) Trim(s, cutset any) (string, error) { return strings.Trim(ss, sc), nil } +// TrimSpace returns the given string, removing leading and trailing whitespace +// as defined by Unicode. +func (ns *Namespace) TrimSpace(s any) (string, error) { + ss, err := cast.ToStringE(s) + if err != nil { + return "", err + } + + return strings.TrimSpace(ss), nil +} + // TrimLeft returns a slice of the string s with all leading characters // contained in cutset removed. func (ns *Namespace) TrimLeft(cutset, s any) (string, error) { diff --git a/tpl/strings/strings_test.go b/tpl/strings/strings_test.go index 4fcd3b59a..0e6039ba1 100644 --- a/tpl/strings/strings_test.go +++ b/tpl/strings/strings_test.go @@ -854,3 +854,30 @@ func TestDiff(t *testing.T) { } } + +func TestTrimSpace(t *testing.T) { + t.Parallel() + c := qt.New(t) + + for _, test := range []struct { + s any + expect any + }{ + {"\n\r test \n\r", "test"}, + {template.HTML("\n\r test \n\r"), "test"}, + {[]byte("\n\r test \n\r"), "test"}, + // errors + {tstNoStringer{}, false}, + } { + + result, err := ns.TrimSpace(test.s) + + if b, ok := test.expect.(bool); ok && !b { + c.Assert(err, qt.Not(qt.IsNil)) + continue + } + + c.Assert(err, qt.IsNil) + c.Assert(result, qt.Equals, test.expect) + } +} |