Skip to content

Commit

Permalink
Merge pull request #895 from planetary-social/feature/detect-urls
Browse files Browse the repository at this point in the history
Don’t include trailing comma in detected URL
  • Loading branch information
joshuatbrown authored Feb 27, 2024
2 parents b412047 + 5898ee4 commit 094f0fb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
6 changes: 3 additions & 3 deletions Nos/Extensions/String+Markdown.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ import Logger
extension String {
/// Find all links in a given string and replaces them with markdown formatted links
func findAndReplaceUnformattedLinks(in string: String) throws -> String {
// swiftlint:disable line_length
// swiftlint:disable:next line_length
let regex = "(?:^|\\s)(?<link>((http|https)?:\\/\\/.)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*))"
// swiftlint:enable line_length
let regularExpression = try NSRegularExpression(pattern: regex)
let wholeRange = NSRange(location: 0, length: string.utf16.count)
if let match = regularExpression.firstMatch(in: string, range: wholeRange) {
Expand All @@ -40,7 +39,8 @@ extension String {
let mutableString = NSMutableString(string: self)
// The following pattern uses rules from the Domain Name System page on Wikipedia:
// https://en.wikipedia.org/wiki/Domain_Name_System#Domain_name_syntax,_internationalization
let regexPattern = "(\\s*)((https?://)?([a-zA-Z0-9][-a-zA-Z0-9]{0,62}\\.){1,127}[a-z]{2,63}[^\\s]*)"
// swiftlint:disable:next line_length
let regexPattern = "(\\s*)((https?://)?([a-zA-Z0-9][-a-zA-Z0-9]{0,62}\\.){1,127}[a-z]{2,63}\\b[-a-zA-Z0-9@:%_\\+.~#?&/=]*)"

do {
let regex = try NSRegularExpression(pattern: regexPattern)
Expand Down
16 changes: 16 additions & 0 deletions NosTests/Extensions/String+MarkdownTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,22 @@ class String_MarkdownTests: XCTestCase {
XCTAssertTrue(actualURLs.isEmpty)
}

func testExtractURLsDoesNotIncludeCommasInURLs() throws {
// Arrange
let string = "Welcome to nos.social, a place for humans"
let expectedString = "Welcome to [nos.social](https://nos.social), a place for humans"
let expectedURLs = [
URL(string: "https://nos.social")!
]

// Act
let (actualString, actualURLs) = string.extractURLs()

// Assert
XCTAssertEqual(actualString, expectedString)
XCTAssertEqual(actualURLs, expectedURLs)
}

func testExtractURLsWithImage() throws {
let string = "Hello, world!https://cdn.ymaws.com/footprints.jpg"
let expectedString = "Hello, world![cdn.ymaws.com...](https://cdn.ymaws.com/footprints.jpg)"
Expand Down

0 comments on commit 094f0fb

Please sign in to comment.