Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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