main.go 907 B

123456789101112131415161718192021222324252627282930
  1. // Package sanitized_anchor_name provides a func to create sanitized anchor names.
  2. //
  3. // Its logic can be reused by multiple packages to create interoperable anchor names
  4. // and links to those anchors.
  5. //
  6. // At this time, it does not try to ensure that generated anchor names
  7. // are unique, that responsibility falls on the caller.
  8. package sanitized_anchor_name // import "github.com/shurcooL/sanitized_anchor_name"
  9. import "unicode"
  10. // Create returns a sanitized anchor name for the given text.
  11. func Create(text string) string {
  12. var anchorName []rune
  13. var futureDash = false
  14. for _, r := range []rune(text) {
  15. switch {
  16. case unicode.IsLetter(r) || unicode.IsNumber(r):
  17. if futureDash && len(anchorName) > 0 {
  18. anchorName = append(anchorName, '-')
  19. }
  20. futureDash = false
  21. anchorName = append(anchorName, unicode.ToLower(r))
  22. default:
  23. futureDash = true
  24. }
  25. }
  26. return string(anchorName)
  27. }