Skip to content

Commit 8d94332

Browse files
committed
fix
1 parent f6dbb31 commit 8d94332

File tree

1 file changed

+19
-18
lines changed

1 file changed

+19
-18
lines changed

ios/HackerNews/Utils/Extensions.swift

Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,30 @@ extension String {
1313
// Basic HTML to Markdown conversion that seems to work decently well in testing
1414
// If we find bugs, maybe move to copying this solution: https://github.com/Dimillian/IceCubesApp/blob/main/Packages/Models/Sources/Models/Alias/HTMLString.swift
1515
func formattedHTML() -> AttributedString {
16-
// Unescape HTML entities in the entire string before handling links
17-
var processedText =
18-
self
19-
.replacingOccurrences(of: "&", with: "&")
20-
.replacingOccurrences(of: ">", with: ">")
21-
.replacingOccurrences(of: "&lt;", with: "<")
22-
.replacingOccurrences(of: "&quot;", with: "\"")
23-
.replacingOccurrences(of: "&#x27;", with: "'")
16+
var processedText = self
2417

25-
// Handle links using regex
26-
// Note: I tried using SwiftSoup at first, but it was having difficulty with edge cases
27-
let linkPattern = #"<a[^>]*href="([^"]*)"[^>]*>(.*?)</a>"#
28-
if let regex = try? NSRegularExpression(pattern: linkPattern) {
29-
let range = NSRange(processedText.startIndex..<processedText.endIndex, in: processedText)
30-
processedText = regex.stringByReplacingMatches(
31-
in: processedText,
32-
range: range,
33-
withTemplate: "[$2]($1)"
34-
)
18+
// Handle links separately via parsing the HTML
19+
if let doc = try? SwiftSoup.parse(processedText) {
20+
if let links = try? doc.select("a") {
21+
for link in links {
22+
if let href = try? link.attr("href"),
23+
let text = try? link.text(),
24+
let htmlLink = try? link.outerHtml()
25+
{
26+
processedText = processedText.replacingOccurrences(
27+
of: htmlLink, with: "[\(text)](\(href))")
28+
}
29+
}
30+
}
3531
}
3632

3733
processedText =
3834
processedText
35+
.replacingOccurrences(of: "&amp;", with: "&")
36+
.replacingOccurrences(of: "&gt;", with: ">")
37+
.replacingOccurrences(of: "&lt;", with: "<")
38+
.replacingOccurrences(of: "&quot;", with: "\"")
39+
.replacingOccurrences(of: "&#x27;", with: "'")
3940
.replacingOccurrences(of: "<p>", with: "\n")
4041
.replacingOccurrences(of: "</p>", with: "\n")
4142
.replacingOccurrences(of: "<br>", with: "\n")

0 commit comments

Comments
 (0)