Skip to content

Instantly share code, notes, and snippets.

@howellcc
Created November 30, 2022 15:27
Show Gist options
  • Save howellcc/8bfe1080dbfc084aae56ecdfb0ca72a3 to your computer and use it in GitHub Desktop.
Save howellcc/8bfe1080dbfc084aae56ecdfb0ca72a3 to your computer and use it in GitHub Desktop.
Replace urls in a text block with anchor tags creating clickable links.
private createAnchorTagsForUrls(message: string): string {
/* As it turns out finding a URL within other text is surprisingly hard. Mainly because spaces are technically legal.
However, if we assume that they are not, the following RegEx does a pretty good job and is still readable. */
const regex: RegExp = /\b(https?|ftp|file):\/\/[\S]+/ig ;
let ret: string = message;
/* Check for href. If this exists we can assume that this string already contains anchor tags and should not have its
urls replaced with anchor tags again */
if(ret.indexOf("href=") < 0){
ret = ret.replace(regex,'<a href="$&" target="_blank">$&</a>');
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment