docsonnet/pkg/slug/slug.go
2020-04-29 16:39:37 +02:00

35 lines
643 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package slug
import (
"regexp"
"strconv"
"strings"
)
type Slugger struct {
occurences map[string]int
}
var (
expWhitespace = regexp.MustCompile(`\s`)
expSpecials = regexp.MustCompile("[\u2000-\u206F\u2E00-\u2E7F\\'!\"#$%&()*+,./:;<=>?@[\\]^`{|}~]")
)
func New() *Slugger {
return &Slugger{
occurences: make(map[string]int),
}
}
func (s *Slugger) Slug(str string) string {
str = expWhitespace.ReplaceAllString(str, "-")
str = expSpecials.ReplaceAllString(str, "")
old := str
if o := s.occurences[str]; o > 0 {
str += "-" + strconv.Itoa(o)
}
s.occurences[old] = s.occurences[old] + 1
return strings.ToLower(str)
}