From a8f0d5a63ebe9483bd8fec8865f2e8a9da90de4c Mon Sep 17 00:00:00 2001 From: "marko.tikvic" Date: Mon, 16 Sep 2019 10:42:10 +0200 Subject: [PATCH] SplitText --- string_util.go | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/string_util.go b/string_util.go index 640f7e1..51f1d1c 100644 --- a/string_util.go +++ b/string_util.go @@ -4,6 +4,7 @@ import ( "fmt" "strconv" "strings" + "unicode" ) const sanitisationPatern = "\"';&*<>=\\`:" @@ -100,6 +101,53 @@ func StringAt(s string, index int) string { return string(s[index]) } +// SplitText ... +func SplitText(s string, maxLen int) (lines []string) { + runes := []rune(s) + + i, start, sep, l := 0, 0, 0, 0 + for i = 0; i < len(runes); i++ { + c := runes[i] + + if unicode.IsSpace(c) { + sep = i + } + + if c == '\n' { + if start != sep { + lines = append(lines, string(runes[start:sep])) + } + start = i + sep = i + l = 0 + } else if l >= maxLen { + if start != sep { + lines = append(lines, string(runes[start:sep])) + sep = i + start = i - 1 + l = 0 + } + } else { + l++ + } + } + if start != i-1 { + lines = append(lines, string(runes[start:i-1])) + } + + return lines +} + +const threeDots = "\u2056\u2056\u2056" + +func LimitTextWithThreeDots(txt string, maxLen int) string { + if len(txt) <= maxLen { + return txt + } + + return txt[:maxLen] + threeDots +} + // SplitStringAtWholeWords ... func SplitStringAtWholeWords(s string, maxLen int) (res []string) { parts := strings.Split(s, " ") @@ -123,4 +171,3 @@ func SplitStringAtWholeWords(s string, maxLen int) (res []string) { return res } - -- 1.8.1.2