【问题标题】:How to render URLs in string as clickable hyperlink?如何将字符串中的 URL 呈现为可点击的超链接?
【发布时间】:2021-10-08 20:34:16
【问题描述】:

我有一个来自后端 API 的 comments(字符串)字段,其中包含长文本,也可能包含 URL。我想将它们呈现为超链接(锚定 HTML 标记)。

我现在的解决方案是使用正则表达式执行字符串替换,将文本中的所有 URL 转换为标签。它工作正常。

但是有没有更好/更全面的方法来做到这一点?也许一些 NPM 包具有更多的功能来呈现不仅仅是 URL(hashtags、@user 等)? 顺便说一句,我大部分时间都在使用 react/angular,任何 JS 推荐都适用。

样本数据:

Hello, My name is John.\n\nThis is my linkedin profile: https://linkedin.com/in/john .\n\nFollow me! Thanks.

预期结果:

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.

【问题讨论】:

  • 有lodash.template、handlebars、ejstemplate、vue、react等库。任你选。 ejstemplate 是流行的快速标记
  • 错误。对不起,我应该让问题更清楚。我正在使用反应。但是,任何 JS 库推荐都足够好。
  • 那么正则表达式可能是正确的方法,因为您必须从中提取网址

标签: javascript html parsing hyperlink anchor


【解决方案1】:

工作 JS (typescript) 函数执行字符串替换 URL 到 &lt;a&gt; 标记。

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);

正则表达式来自:https://stackoverflow.com/a/5717133/6122411

【讨论】:

    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 2021-05-13
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 2019-02-10
    相关资源
    最近更新 更多