Created
June 24, 2022 09:08
-
-
Save davidsharp/51173d39cd9f6f9929f411c07f0317f3 to your computer and use it in GitHub Desktop.
Ever so slightly shorter version of the Autolink component found in 30 Seconds of Knowledge
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
function AutoLink({ text }) { | |
const delimiter = /((?:https?:\/\/)?(?:(?:[a-z0-9]?(?:[a-z0-9\-]{1,61}[a-z0-9])?\.[^\.|\s])+[a-z\.]*[a-z]+|(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})(?::\d{1,5})*[a-z0-9.,_\/~#&=;%+?\-\\(\\)]*)/gi; | |
return ( | |
<React.Fragment> | |
{text.split(delimiter).map((word,i) => { | |
const isUrl = i%2; | |
return isUrl ? (<a href={word.startsWith("http") ? word : `http://${word}`}>{word}</a>) : word; | |
})} | |
</React.Fragment> | |
); | |
} |
This naturally also saves a regex running over each item in the array, for which I'm sure there are mostly negligible gains
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The behaviour's less clear, but due to the way
split
works, the URLs will always be the even entries (henceisUrl = i%2
)