diff --git a/docs/strings.md b/docs/strings.md index 86940f53..210bec2b 100644 --- a/docs/strings.md +++ b/docs/strings.md @@ -118,11 +118,17 @@ trunc 5 "hello world" The above produces `hello`. +``` +trunc -5 "hello world" +``` + +The above produces `world`. + ## abbrev Truncate a string with ellipses (`...`) -Parameters: +Parameters: - max length - the string @@ -284,7 +290,7 @@ len $fish | plural "one anchovy" "many anchovies" ``` In the above, if the length of the string is 1, the first argument will be -printed (`one anchovy`). Otherwise, the second argument will be printed +printed (`one anchovy`). Otherwise, the second argument will be printed (`many anchovies`). The arguments are: @@ -338,10 +344,10 @@ Swap the case of a string using a word based algorithm. Conversion algorithm: -- Upper case character converts to Lower case -- Title case character converts to Lower case -- Lower case character after Whitespace or at start converts to Title case -- Other Lower case character converts to Upper case +- Upper case character converts to Lower case +- Title case character converts to Lower case +- Lower case character after Whitespace or at start converts to Title case +- Other Lower case character converts to Upper case - Whitespace is defined by unicode.IsSpace(char). ``` diff --git a/strings.go b/strings.go index 943fa3e8..76cdf537 100644 --- a/strings.go +++ b/strings.go @@ -187,10 +187,13 @@ func strval(v interface{}) string { } func trunc(c int, s string) string { - if len(s) <= c { - return s + if c < 0 && len(s)+c > 0 { + return s[len(s)+c:] + } + if c >= 0 && len(s) > c { + return s[:c] } - return s[0:c] + return s } func join(sep string, v interface{}) string { diff --git a/strings_test.go b/strings_test.go index 2339d5c1..a0c785c9 100644 --- a/strings_test.go +++ b/strings_test.go @@ -29,6 +29,18 @@ func TestTrunc(t *testing.T) { if err := runt(tpl, "foo"); err != nil { t.Error(err) } + tpl = `{{ "baaaaaar" | trunc -3 }}` + if err := runt(tpl, "aar"); err != nil { + t.Error(err) + } + tpl = `{{ "baaaaaar" | trunc -999 }}` + if err := runt(tpl, "baaaaaar"); err != nil { + t.Error(err) + } + tpl = `{{ "baaaaaz" | trunc 0 }}` + if err := runt(tpl, ""); err != nil { + t.Error(err) + } } func TestQuote(t *testing.T) {