Created
May 2, 2021 21:33
-
-
Save wojtekmaj/5ca58013ed99fbd5ed0bde0b7edda8e4 to your computer and use it in GitHub Desktop.
Add links to text in React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const pattern = /https?:\/\/[^\s]*/g; | |
function formatLink(url, props) { | |
if (!url) { | |
return ''; | |
} | |
let host; | |
let pathname; | |
try { | |
({ host, pathname } = new URL(url)); | |
} catch (err) { | |
return url; | |
} | |
return ( | |
<a | |
{...props} | |
href={url} | |
rel="noopener noreferrer" | |
target="_blank" | |
> | |
{host + (pathname !== '/' ? pathname : '')} | |
</a> | |
); | |
} | |
function addLinks(text) { | |
const splitText = text.split(pattern); | |
if (splitText.length <= 1) { | |
return text; | |
} | |
const matches = text.match(pattern); | |
return splitText.reduce((arr, element, index) => (matches[index] ? [ | |
...arr, | |
element, | |
formatLink(matches[index], { key: index }), | |
] : [...arr, element]), []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment