Skip to content

Commit

Permalink
Merge pull request #56 from sirwart/improve-slugify-compatibility
Browse files Browse the repository at this point in the history
Remove leading and trailing hyphens from slugs to match jekyll behavior
  • Loading branch information
danog authored Dec 6, 2023
2 parents 2ebb809 + be5135f commit f1794a8
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
7 changes: 6 additions & 1 deletion utils/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,15 @@ func SafeReplaceAllStringFunc(re *regexp.Regexp, src string, repl func(m string)
}

var nonAlphanumericSequenceMatcher = regexp.MustCompile(`[^[:alnum:]]+`)
var leadingOrTrailingHyphenMatcher = regexp.MustCompile(`(^-|-$)`)

// Slugify replaces each sequence of non-alphanumerics by a single hyphen
func Slugify(s string) string {
return strings.ToLower(nonAlphanumericSequenceMatcher.ReplaceAllString(s, "-"))
slug := strings.ToLower(nonAlphanumericSequenceMatcher.ReplaceAllString(s, "-"))

// remove leading and trailing hyphen
slug = leadingOrTrailingHyphenMatcher.ReplaceAllString(slug, "")
return slug
}

// StringArrayToMap creates a map for use as a set.
Expand Down
1 change: 1 addition & 0 deletions utils/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func TestSlugify(t *testing.T) {
require.Equal(t, "ab-c", Slugify("ab-c"))
require.Equal(t, "ab-c", Slugify("ab()[]c"))
require.Equal(t, "ab123-cde-f-g", Slugify("ab123(cde)[]f.g"))
require.Equal(t, "abc", Slugify("abc?"))
}

func TestStringArrayToMap(t *testing.T) {
Expand Down

0 comments on commit f1794a8

Please sign in to comment.