Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/util/__tests__/link-external-urls.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import linkExternalUrls from '../link-external-urls'

const anchor = (url: string) => `<a target="_blank" rel="noopener noreferrer" href="${url}">${url}</a>`

describe('linkExternalUrls', () => {
it('wraps a plain URL in an anchor', () => {
expect(linkExternalUrls('https://x.com'))
.toBe(anchor('https://x.com'))
})

it('keeps wrapping quotes outside the link', () => {
expect(linkExternalUrls('"https://x.com"'))
.toBe(`"${anchor('https://x.com')}"`)
})

it('keeps a sentence-ending period as plain text', () => {
expect(linkExternalUrls('see https://x.com.'))
.toBe(`see ${anchor('https://x.com')}.`)
})

it('keeps a trailing comma in mid-sentence as plain text', () => {
expect(linkExternalUrls('go to https://x.com, then stop'))
.toBe(`go to ${anchor('https://x.com')}, then stop`)
})

it('keeps wrapping parentheses outside the link', () => {
expect(linkExternalUrls('(https://x.com)'))
.toBe(`(${anchor('https://x.com')})`)
})

it('preserves balanced parentheses inside the URL', () => {
const url = 'https://en.wikipedia.org/wiki/Foo_(bar)'

expect(linkExternalUrls(url))
.toBe(anchor(url))
})

it('links multiple URLs in one string', () => {
expect(linkExternalUrls('a https://x.com b https://y.com'))
.toBe(`a ${anchor('https://x.com')} b ${anchor('https://y.com')}`)
})

it('returns text without a URL unchanged', () => {
expect(linkExternalUrls('no link here'))
.toBe('no link here')
})
})
26 changes: 24 additions & 2 deletions src/util/link-external-urls.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
const externalUrlRegExp = /(https?:\/\/\S+)/gi
const externalUrlRegExp = /https?:\/\/[^\s<>"'`]+/gi

const linkExternalUrls = (text: string) => text.replace(externalUrlRegExp, '<a target="_blank" href="$1">$1</a>')
const trailingPunctuationRegExp = /[?!.,:*_~]+$/

// Trim trailing punctuation and unmatched closing parens (GFM autolink rules).
const trimUrl = (url: string): string => {
let result = url.replace(trailingPunctuationRegExp, '')

while (
result.endsWith(')') &&
(result.match(/\)/g)?.length ?? 0) > (result.match(/\(/g)?.length ?? 0)
) {
result = result.slice(0, -1).replace(trailingPunctuationRegExp, '')
}

return result
}

const linkExternalUrls = (text: string) => text.replace(externalUrlRegExp, (match) => {
const url = trimUrl(match)

const trailing = match.slice(url.length)

return `<a target="_blank" rel="noopener noreferrer" href="${url}">${url}</a>${trailing}`
})

export default linkExternalUrls