【发布时间】: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