strings.go 735 B

123456789101112131415161718192021222324252627282930313233
  1. package utils
  2. import (
  3. "strings"
  4. "github.com/microcosm-cc/bluemonday"
  5. )
  6. // StripHTML will strip HTML tags from a string.
  7. func StripHTML(s string) string {
  8. p := bluemonday.NewPolicy()
  9. return p.Sanitize(s)
  10. }
  11. // MakeSafeStringOfLength will take a string and strip HTML tags,
  12. // trim whitespace, and limit the length.
  13. func MakeSafeStringOfLength(s string, length int) string {
  14. newString := s
  15. newString = StripHTML(newString)
  16. // Convert utf-8 string into Unicode code points.
  17. codePoints := []rune(newString)
  18. if len(codePoints) > length {
  19. codePoints = codePoints[:length]
  20. }
  21. newString = string(codePoints)
  22. newString = strings.ReplaceAll(newString, "\r", "")
  23. newString = strings.TrimSpace(newString)
  24. return newString
  25. }