Skip to content

Instantly share code, notes, and snippets.

@sethlilly
Created September 26, 2019 20:46
Show Gist options
  • Save sethlilly/99f6ed7aedab59bd229ba06cbed3b261 to your computer and use it in GitHub Desktop.
Save sethlilly/99f6ed7aedab59bd229ba06cbed3b261 to your computer and use it in GitHub Desktop.
Swift toKebabCase String Extension
//
// ToKebabCase.swift
//
// This Swift String extension removes punctuation, replaces spaces with dashes, and lowercases the string.
//
// Usage:
//
// let uglyString = "This, my friends, is an ugly string, full of punctuation. Yuck."
// let prettyString = uglyString.toKebabCase()
//
// print(prettyString) // returns this-my-friends-is-an-ugly-string-full-of-punctuation-yuck
//
// Copyright © 2019 Seth Lilly. But you can use it because I <3 you.
//
extension String {
func toKebabCase() -> String {
return self.replacingOccurrences(
of: #"[^\w\s]"#,
with: "",
options: .regularExpression
).replacingOccurrences(
of: #"[\s]"#,
with: "-",
options: .regularExpression
).lowercased()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment