-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
55 lines (49 loc) · 1.59 KB
/
main.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
// Package slugify provide a function that
// gives a non accentuated and minus separated string from a
// accentuated string. The code is based from a Javascript function
// that you can get here:
// http://irz.fr/slugme-permalien-javascript-slug/
package slugify
import (
"regexp"
"strings"
)
// Replacement structure
type replacement struct {
re *regexp.Regexp
ch string
}
// Build regexps and replacements
var (
rExps = []replacement{
{re: regexp.MustCompile(`[\xC0-\xC6]`), ch: "A"},
{re: regexp.MustCompile(`[\xE0-\xE6]`), ch: "a"},
{re: regexp.MustCompile(`[\xC8-\xCB]`), ch: "E"},
{re: regexp.MustCompile(`[\xE8-\xEB]`), ch: "e"},
{re: regexp.MustCompile(`[\xCC-\xCF]`), ch: "I"},
{re: regexp.MustCompile(`[\xEC-\xEF]`), ch: "i"},
{re: regexp.MustCompile(`[\xD2-\xD6]`), ch: "O"},
{re: regexp.MustCompile(`[\xF2-\xF6]`), ch: "o"},
{re: regexp.MustCompile(`[\xD9-\xDC]`), ch: "U"},
{re: regexp.MustCompile(`[\xF9-\xFC]`), ch: "u"},
{re: regexp.MustCompile(`[\xC7-\xE7]`), ch: "c"},
{re: regexp.MustCompile(`[\xD1]`), ch: "N"},
{re: regexp.MustCompile(`[\xF1]`), ch: "n"},
}
spacereg = regexp.MustCompile(`\s+`)
noncharreg = regexp.MustCompile(`[^A-Za-z0-9-]`)
minusrepeatreg = regexp.MustCompile(`\-{2,}`)
)
// Marshal function returns slugifies string "s"
func Marshal(s string, lower ...bool) string {
for _, r := range rExps {
s = r.re.ReplaceAllString(s, r.ch)
}
if len(lower) > 0 && lower[0] {
s = strings.ToLower(s)
}
s = spacereg.ReplaceAllString(s, "-")
s = noncharreg.ReplaceAllString(s, "")
s = minusrepeatreg.ReplaceAllString(s, "-")
return s
}