-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathslugify.go
60 lines (53 loc) · 1.24 KB
/
slugify.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package slugify
import (
"regexp"
"strings"
)
var replacements = map[rune]string{
'á': "a",
'à': "a",
'ä': "a",
'â': "a",
'é': "e",
'è': "e",
'ë': "e",
'ê': "e",
'í': "i",
'ì': "i",
'i': "i",
'î': "i",
'ó': "o",
'ò': "o",
'ö': "o",
'ő': "o",
'ô': "o",
'ú': "u",
'ù': "u",
'ü': "u",
'ű': "u",
'ç': "c",
'·': "-",
'–': "-",
'/': "-",
'_': "-",
',': "-",
':': "-",
';': "-",
'\'': "", // collapses "adam's" to "adams"
}
func S(str string) string {
str = strings.ToLower(strings.TrimSpace(str)) // Trim all whitespace and special characters at beginning and end, then Lower-Case
newstr := ""
// Iterate over string, for each character check if there is a replacement, if so, append it to newstr, if not, append original value to newstr
for _, char := range str {
if replacement, ok := replacements[char]; ok {
newstr += replacement
} else {
newstr += string(char)
}
}
newstr = regexp.MustCompile("[^a-z0-9-]").ReplaceAllString(newstr, "-") // Remove invalid chars (spaces are invalid)
newstr = regexp.MustCompile("-+").ReplaceAllString(newstr, "-") // Collapse dashes
newstr = strings.Trim(newstr, "-") // Trim dashes from beginning and end
return newstr
}