underscore.go 715 B

1234567891011121314151617181920212223242526272829303132333435
  1. package flect
  2. import (
  3. "strings"
  4. "unicode"
  5. )
  6. // Underscore a string
  7. // bob dylan = bob_dylan
  8. // Nice to see you! = nice_to_see_you
  9. // widgetID = widget_id
  10. func Underscore(s string) string {
  11. return New(s).Underscore().String()
  12. }
  13. // Underscore a string
  14. // bob dylan = bob_dylan
  15. // Nice to see you! = nice_to_see_you
  16. // widgetID = widget_id
  17. func (i Ident) Underscore() Ident {
  18. out := make([]string, 0, len(i.Parts))
  19. for _, part := range i.Parts {
  20. var x strings.Builder
  21. x.Grow(len(part))
  22. for _, c := range part {
  23. if unicode.IsLetter(c) || unicode.IsDigit(c) {
  24. x.WriteRune(c)
  25. }
  26. }
  27. if x.Len() > 0 {
  28. out = append(out, x.String())
  29. }
  30. }
  31. return New(strings.ToLower(strings.Join(out, "_")))
  32. }