ref: 028b356787426dbc190ce9868fbc9a6400c2996e
parent: e9f87c4e3feee937d05504763935805fec26213c
author: Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
date: Fri Jul 3 06:34:40 EDT 2020
tpl/strings: Add strings.Count Fixes #7453
--- a/tpl/strings/init.go
+++ b/tpl/strings/init.go
@@ -51,6 +51,13 @@
[][2]string{},
)
+ ns.AddMethodMapping(ctx.Count,
+ nil,
+ [][2]string{
+ {`{{"aabab" | strings.Count "a" }}`, `3`},
+ },
+ )
+
ns.AddMethodMapping(ctx.FindRE,
[]string{"findRE"},
[][2]string{
--- a/tpl/strings/strings.go
+++ b/tpl/strings/strings.go
@@ -18,6 +18,7 @@
"errors"
"fmt"
"html/template"
+ "strings"
_strings "strings"
"unicode/utf8"
@@ -88,6 +89,20 @@
}
return counter, nil
+}
+
+// Count counts the number of non-overlapping instances of substr in s.
+// If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
+func (ns *Namespace) Count(substr, s interface{}) (int, error) {
+ substrs, err := cast.ToStringE(substr)
+ if err != nil {
+ return 0, _errors.Wrap(err, "Failed to convert substr to string")
+ }
+ ss, err := cast.ToStringE(s)
+ if err != nil {
+ return 0, _errors.Wrap(err, "Failed to convert s to string")
+ }
+ return strings.Count(ss, substrs), nil
}
// Chomp returns a copy of s with all trailing newline characters removed.