Archived
1
This repository has been archived on 2022-11-04. You can view files and clone it, but cannot push or open issues or pull requests.
fwzookeeper/vendor/github.com/kirillDanshin/myutils/strCrop.go

32 lines
489 B
Go
Raw Normal View History

2018-12-22 17:38:56 +04:00
package myutils
import "regexp"
var cropRgx *regexp.Regexp
// StrCrop crops a string like you want in blog previews
func StrCrop(str string, length int) string {
if len(str) <= length {
return str
}
if cropRgx == nil {
cropRgx = regexp.MustCompile(`[\s,.-]`)
}
var (
lastStop int
runeStr = []rune(str)
)
for i, r := range runeStr {
if cropRgx.MatchString(string(r)) {
lastStop = i
}
if i >= length {
return string(runeStr[:lastStop])
}
}
return str
}