-
-
Save danhixon/f5c7c95090c2fafd30ad2812ca1a5bd2 to your computer and use it in GitHub Desktop.
A truncate function extension for the default String type that honors words.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String { | |
/// Truncates the string to length number of characters and | |
/// doesn't truncate within a word. | |
/// appends optional trailing string if longer | |
func truncate(_ length: Int, wordSeparator: String = " ", trailing: String = "…") -> String { | |
// only truncate if needed | |
if self.characters.count > length { | |
// count the trailing characters first | |
var cumulativeCharacters = trailing.characters.count | |
let words = self.components(separatedBy: wordSeparator) | |
var wordsToInclude:[String] = [] | |
for word in words { | |
cumulativeCharacters += word.characters.count + 1 | |
print("\(word) is \(word.characters.count) characters long, cumulative: \(cumulativeCharacters)") | |
if cumulativeCharacters <= length { | |
wordsToInclude.append(word) | |
} else { | |
return wordsToInclude.joined(separator: wordSeparator) + trailing | |
} | |
} | |
return self.substring(to: self.characters.index(self.startIndex, offsetBy: length)) + trailing | |
} else { | |
return self | |
} | |
} | |
} | |
// Examples: | |
"This is a long string".truncate(15) // "This is a…" | |
"This-is-a-long-string".truncate(15, wordSeparator: "-") // "This-is-a…" | |
"This is a long string".truncate(15, wordSeparator: " ", trailing: " more…") // "This is more…" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated for swift 3 and variable length "trailing" values.