Skip to content

Instantly share code, notes, and snippets.

Created September 19, 2018 14:12
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Slugify routine in Swift 4.1
// Slugify
// A String extension that converts a text string into a valid URL
// Derived from
// By Jeff Algera -
extension String {
private static let allowedCharacters = NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")
public func slugify() -> String {
let cocoaString = NSMutableString(string: self) as CFMutableString
CFStringTransform(cocoaString, nil, kCFStringTransformToLatin, false)
CFStringTransform(cocoaString, nil, kCFStringTransformStripCombiningMarks, false)
CFStringLowercase(cocoaString, .none)
return String(cocoaString)
.components(separatedBy: String.allowedCharacters.inverted)
.filter { $0 != "" }
.joined(separator: "-")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment