Skip to content

Instantly share code, notes, and snippets.

@staydecent
Created May 14, 2020 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save staydecent/f09bd043556b0100fdf7fda1b185c698 to your computer and use it in GitHub Desktop.
Save staydecent/f09bd043556b0100fdf7fda1b185c698 to your computer and use it in GitHub Desktop.
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.,_\/~#&=;%+?\-\\(\\)]*)/ig
let strStartsWith = (str, prefix) => {
return str.slice(0, prefix.length) === prefix;
}
function Linkify ({ text, anchorProps = {} }) {
if (!text) return
return text.split(delimiter).map(word => {
const match = word.match(delimiter)
if (match) {
const url = match[0]
const segments = url.split('/')
// no scheme given, so check host portion length
if (segments[1] !== '' && segments[0].length < 5) {
return word
}
return (
<a href={strStartsWith(url, 'http') ? url : `http://${url}`} {...anchorProps}>{url}</a>
)
} else {
return word
}
})
}
function App () {
const text = 'Hey check this out, http://inputlogic.ca cool eh?'
return (
<div>
<h2>Linkify:</h2>
<Linkify text={text} />
</div>
)
}
ReactDOM.render(<App />, document.querySelector("#app"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment