Skip to content

Instantly share code, notes, and snippets.

@jb-alvarado
Created June 30, 2021 13:15
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 jb-alvarado/d85e299131bc3fee5d4efd3e628771de to your computer and use it in GitHub Desktop.
Save jb-alvarado/d85e299131bc3fee5d4efd3e628771de to your computer and use it in GitHub Desktop.
Find URLs in text and create links out of it.
function urlify(text) {
const hyperlink = /<a [^>]+>([\w\d./=:"-]+)<\/a>/g
const urlRegex = /(https?:\/\/|www\.)([\w\d./-]+)/g
return text.replace(/(?:\r\n|\r|\n)/g, '<br>')
.replace(hyperlink, '$1')
.replace(urlRegex, (url, protoOrSub, domain) => {
domain = domain.replace(/\/$/, '')
if (protoOrSub.match(/https?/)) {
return `<a href="${protoOrSub}${domain}" target="_blank">${domain}</a>`
} else if (protoOrSub === 'www.') {
return `<a href="http://www.${domain}" target="_blank">www.${domain}</a>`
} else {
return url
}
})
}
console.log(urlify('Link: http://www.domain1.com/clients/,'))
console.log(urlify('Link: https://www.domain2.com/clients?'))
console.log(urlify('Link: www.domain3.com/clients'))
console.log(urlify('Link: <a href="https://www.domain4.com/clients" target="_blank">https://www.domain4.com/clients</a>!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment