Created
September 19, 2018 14:12
-
-
Save algera/128a87bf194e533eead881705a9c87f3 to your computer and use it in GitHub Desktop.
Slugify routine in Swift 4.1
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
//// | |
// Slugify | |
// A String extension that converts a text string into a valid URL | |
// Derived from https://github.com/paulyoung/Slugify/blob/master/Slugify/Slugify.swift | |
// By Jeff Algera - jeffalgera.com | |
//// | |
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