Skip to content

Commit

Permalink
fix edge case in truncate function allowing too long slugs
Browse files Browse the repository at this point in the history
  • Loading branch information
Romain Poirot committed Aug 1, 2022
1 parent e104167 commit 3649d7c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
20 changes: 7 additions & 13 deletions slug.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,21 +150,15 @@ func smartTruncate(text string) string {
return text
}

var truncated string
words := strings.SplitAfter(text, "-")
// If MaxLength is smaller than length of the first word return word
// truncated after MaxLength.
if len(words[0]) > MaxLength {
return words[0][:MaxLength]
}
for _, word := range words {
if len(truncated)+len(word)-1 <= MaxLength {
truncated = truncated + word
} else {
break
// If slug is too long, we need to find the last '-' before MaxLength, and
// we cut there.
// If we don't find any, we have only one word, and we cut at MaxLength.
for i := MaxLength - 1; i >= 0; i-- {
if text[i] == '-' {
return text[:i]
}
}
return strings.Trim(truncated, "-")
return text[:MaxLength]
}

// IsSlug returns True if provided text does not contain white characters,
Expand Down
1 change: 1 addition & 0 deletions slug_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ func TestSlugMakeSmartTruncate(t *testing.T) {
{"DOBROSLAWZYBORT", 100, "dobroslawzybort"},
{"Dobroslaw Zybort", 100, "dobroslaw-zybort"},
{"Dobroslaw Zybort", 12, "dobroslaw"},
{"Dobroslaw Zybort", 15, "dobroslaw"},
{" Dobroslaw Zybort ?", 12, "dobroslaw"},
{"Ala ma 6 kotów.", 10, "ala-ma-6"},
{"Dobrosław Żybort", 5, "dobro"},
Expand Down

0 comments on commit 3649d7c

Please sign in to comment.