Skip to content

Instantly share code, notes, and snippets.

@danhixon
Forked from carlhunterroach/string-truncate.swift
Last active March 6, 2017 22:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danhixon/f5c7c95090c2fafd30ad2812ca1a5bd2 to your computer and use it in GitHub Desktop.
Save danhixon/f5c7c95090c2fafd30ad2812ca1a5bd2 to your computer and use it in GitHub Desktop.
A truncate function extension for the default String type that honors words.
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…"
@danhixon
Copy link
Author

danhixon commented Mar 6, 2017

Updated for swift 3 and variable length "trailing" values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment