I have a comments
(string) field from backend API which contains long text and possible with URLs too. I want to render them as hyperlinks (anchor HTML tags).
The solution I have right now, is to perform string replace using regex, to convert all URLs in the text into tags. It's working fine.
But is there better/more holistic way to do this? Maybe some NPM package that have more features to render more than just URLs(hashtags, @user, etc)? Btw, I'm using react/angular most of the time, any JS recommendation is applicable.
Sample data:
Hello, My name is John.\n\nThis is my linkedin profile: https://linkedin.com/in/john .\n\nFollow me! Thanks.
Expected outcome:
Hello, My name is John.
This is my linkedin profile: <a href="https://linkedin.com/in/john">https://linkedin.com/in/john</a> .
Follow me! Thanks.
Working JS (typescript) function to perform string replace URL to <a>
tag.
const Regex_Url_Str = "(https?:\\/\\/)?" // protocol
+ "((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" // domain name
+ "((\\d{1,3}\\.){3}\\d{1,3}))" // OR ip (v4) address
+ "(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" // port and path
+ "(\\?[;&a-z\\d%_.~+=-]*)?" // query string
+ "(\\#[-a-z\\d_]*)?";
const StringUtil = {
isValidUrl: (str: string): boolean => new RegExp(Regex_Url_Str, "i").test(str),
parseHyperlinks: (str: string): string => str.replaceAll(new RegExp(Regex_Url_Str, "gim"), "<a target=\"_blank\" rel=\"noreferrer\" href=\"$&\">$&</a>"),
};
export default StringUtil;
import StringUtil from "../utils/string.ts";
const str = "your_text";
const parsed = StringUtil.parseHyperlinks(str);
The regex is from: https://stackoverflow.com/a/5717133/6122411