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 } -