Skip to content

Instantly share code, notes, and snippets.

@nitrag
Last active October 25, 2022 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitrag/d710446962e0bf36bcdae0a7552973f7 to your computer and use it in GitHub Desktop.
Save nitrag/d710446962e0bf36bcdae0a7552973f7 to your computer and use it in GitHub Desktop.
Convert HTML into Markdown for use in SwiftUI Text views.
//
// For use in SwiftUI Text() views
// Supports Italic, Bold and Links
// Feedback welcome!
extension String {
@available(iOS 15, *)
func toMarkdown() -> String {
var transformed = self
.replacingOccurrences(of: "<i>\\s?+", with: "*", options: .regularExpression, range: nil) /// italic
.replacingOccurrences(of: "\\s?+</i>", with: "*", options: .regularExpression, range: nil) /// italic
.replacingOccurrences(of: "<b>\\s?+", with: "**", options: .regularExpression, range: nil) /// bold
.replacingOccurrences(of: "\\s?+</b>", with: "**", options: .regularExpression, range: nil) /// bold
.replacingOccurrences(of: "<strong>\\s?+", with: "**", options: .regularExpression, range: nil) /// bold
.replacingOccurrences(of: "\\s?+</strong>", with: "**", options: .regularExpression, range: nil) /// bold
if #available(iOS 16.0, *) {
transformed = transformed
.replacing(/<a\s+href=.(.*?).>(.*)<\/a>/.ignoresCase()) { match in
return "[\(match.2)](\(match.1))"
}
}
return transformed
.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil) /// cleanup misc html
}
}
// Example:
Text(.init(myText.toMarkdown()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment