Created
June 30, 2021 13:15
-
-
Save jb-alvarado/d85e299131bc3fee5d4efd3e628771de to your computer and use it in GitHub Desktop.
Find URLs in text and create links out of it.
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 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