rune.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package util
  4. import (
  5. "strings"
  6. strip "github.com/grokify/html-strip-tags-go"
  7. )
  8. // TruncateRune 截断字符串长度为length的子串,不限制汉字或英文
  9. // 输入:length,截止的字数,包括汉字和英文的个数
  10. // 输出:没有空格[ ]、换行[\n]、制表符[\t]的字符串
  11. func TruncateRune(s string, length int) string {
  12. // 删除空格与换行字符
  13. s = strings.Replace(s, " ", "", -1)
  14. s = strings.Replace(s, "\n", "", -1)
  15. s = strings.Replace(s, "\t", "", -1)
  16. rs := []rune(s)
  17. len := len(rs)
  18. if length > len {
  19. length = len
  20. }
  21. return string(rs[0:length])
  22. }
  23. // TruncateRuneNoHtmlTags 截断字符串长度为length的子串,不限制汉字或英文
  24. // 输入:length,截止的字数,包括汉字和英文的个数
  25. // 输出:没有空格[ ]、换行[\n]、制表符[\t]和html标签的字符串
  26. func TruncateRuneNoHtmlTags(s string, length int) string {
  27. // 删除空格与换行字符
  28. s = strings.Replace(s, " ", "", -1)
  29. s = strings.Replace(s, "\n", "", -1)
  30. s = strings.Replace(s, "\t", "", -1)
  31. s = strip.StripTags(s)
  32. rs := []rune(s)
  33. len := len(rs)
  34. if length > len {
  35. length = len
  36. }
  37. return string(rs[0:length])
  38. }