|
| 1 | +import Foundation |
| 2 | + |
| 3 | +// From |
| 4 | +// https://github.com/dirtyhenry/swift-blocks/blob/4e6b2fb079edb0ab0951a8fce061ee308c9d3503/Sources/Blocks/Extensions/StringProtocol.swift |
| 5 | + |
| 6 | +public extension StringProtocol { |
| 7 | + /// Converts the string into a URL-friendly slug. |
| 8 | + /// |
| 9 | + /// This method transforms the string to lowercase, removes accents and combining marks, replaces spaces and |
| 10 | + /// non-alphanumeric characters with hyphens, and trims leading and trailing hyphens. |
| 11 | + /// |
| 12 | + /// - Returns: A URL-friendly slug representation of the string. |
| 13 | + /// |
| 14 | + /// # Usage Example # |
| 15 | + /// ``` |
| 16 | + /// let exampleString = "Hello, World! This is an example string with accents: é, è, ê, ñ." |
| 17 | + /// let slugifiedString = exampleString.slugify() |
| 18 | + /// print(slugifiedString) // Output: "hello-world-this-is-an-example-string-with-accents-e-e-e-n" |
| 19 | + /// ``` |
| 20 | + func slugify() -> String { |
| 21 | + var slug = lowercased() |
| 22 | + |
| 23 | + // Remove accents and combining marks |
| 24 | + slug = slug.applyingTransform(.toLatin, reverse: false) ?? slug |
| 25 | + slug = slug.applyingTransform(.stripDiacritics, reverse: false) ?? slug |
| 26 | + slug = slug.applyingTransform(.stripCombiningMarks, reverse: false) ?? slug |
| 27 | + |
| 28 | + // Replace spaces and non-alphanumeric characters with hyphens |
| 29 | + slug = slug.replacingOccurrences( |
| 30 | + of: "[\\+]+", with: "+plus+", options: .regularExpression |
| 31 | + ) |
| 32 | + slug = slug.replacingOccurrences( |
| 33 | + of: "[^a-z0-9]+", with: "-", options: .regularExpression |
| 34 | + ) |
| 35 | + |
| 36 | + // Trim hyphens from the start and end |
| 37 | + slug = slug.trimmingCharacters(in: CharacterSet(charactersIn: "-")) |
| 38 | + |
| 39 | + if !isEmpty, slug.isEmpty { |
| 40 | + if let extendedSelf = applyingTransform(.toUnicodeName, reverse: false)? |
| 41 | + .replacingOccurrences(of: "\\N", with: ""), self != extendedSelf |
| 42 | + // swiftlint:disable:next opening_brace |
| 43 | + { |
| 44 | + return extendedSelf.slugify() |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return slug |
| 49 | + } |
| 50 | +} |
0 commit comments