Skip to content

Instantly share code, notes, and snippets.

@tvler
Last active October 29, 2022 01:04
Show Gist options
  • Save tvler/07f442d682744b6fa872e6a5086e3715 to your computer and use it in GitHub Desktop.
Save tvler/07f442d682744b6fa872e6a5086e3715 to your computer and use it in GitHub Desktop.
Turn a string into JSX with autolinks
type LinkifiedString = Array<string | JSX.Element> | string | null | undefined
/**
* Turn a string into JSX with autolinks
*/
export function getLinkifiedString(str: string | null | undefined): LinkifiedString {
try {
// Group by whitespace (wrapping regex in parens keeps matched results in the array)
const substrings = str?.split(/(\s+)/g)
if (!substrings?.length) {
return null
}
const l = linkify()
const jsx: LinkifiedString = []
for (let i = 0; i < substrings.length; i++) {
const substring = substrings[i]
if (substring === undefined) {
continue
}
const match = l.match(substring)?.[0]
const jsxItem = match ? (
<a
href={match.url}
key={i + substring}
rel="noreferrer"
target="_blank"
>
{match.text}
</a>
) : (
substring
)
jsx.push(jsxItem)
}
return jsx
} catch (err) {
return str
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment