Last active
September 23, 2024 21:27
-
-
Save kiennt2/c9a489369562c424c793b8883b98802e to your computer and use it in GitHub Desktop.
Convert URL Text Into Clickable HTML Link Using JavaScript
This file contains hidden or 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 Linkify(inputText) { | |
//URLs starting with http://, https://, or ftp:// | |
var replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim; | |
var replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>'); | |
//URLs starting with www. (without // before it, or it'd re-link the ones done above) | |
var replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim; | |
var replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>'); | |
//Change email addresses to mailto:: links | |
var replacePattern3 = /(([a-zA-Z0-9_\-\.]+)@[a-zA-Z_]+?(?:\.[a-zA-Z]{2,6}))+/gim; | |
var replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>'); | |
return replacedText | |
} |
What if need to remove these parentheses(curve brackets) '(' and ')' from inputext ?
Can add following at the top but what could be the possibility if needed in existing lines ?
var replacePattern4 = /[()]/g;
replacedText = inputText.replace(replacePattern4, '');
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saved me a bunch of time! I added some look behind to make sure I wasn't converting links which were already in an anchor tag,