Last active
May 18, 2019 03:13
-
-
Save adamgraham/79d4f86fdc36601e564fd3625a8687d2 to your computer and use it in GitHub Desktop.
An extension of the Swift String type to provide kebab case formatting.
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
/// An extension to format strings in *kebab case*. | |
extension String { | |
/// A collection of all the words in the string by separating out any punctuation and spaces. | |
var words: [String] { | |
return components(separatedBy: CharacterSet.alphanumerics.inverted).filter { !$0.isEmpty } | |
} | |
/// Returns a lowercased copy of the string with punctuation removed and spaces replaced | |
/// by a single hyphen, e.g., "the-quick-brown-fox-jumps-over-the-lazy-dog". | |
/// | |
/// *Lower kebab case* (or, illustratively, *kebab-case*) is also known as *spinal case*, | |
/// *param case*, *Lisp case*, and *dash case*. | |
func lowerKebabCased() -> String { | |
return self.words.map({ $0.lowercased() }).joined(separator: "-") | |
} | |
/// Returns an uppercased copy of the string with punctuation removed and spaces replaced | |
/// by a single hyphen, e.g., "THE-QUICK-BROWN-FOX-JUMPS-OVER-THE-LAZY-DOG". | |
/// | |
/// *Upper kebab case* (or, illustratively, *KEBAB-CASE*) is also known as *train case*. | |
func upperKebabCased() -> String { | |
return self.words.map({ $0.uppercased() }).joined(separator: "-") | |
} | |
/// Returns a copy of the string with punctuation removed and spaces replaced by a single | |
/// hyphen, e.g., "The-quick-brown-fox-jumps-over-the-lazy-dog". Upper and lower casing | |
/// is maintained from the original string. | |
func mixedKebabCased() -> String { | |
return self.words.joined(separator: "-") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment