【发布时间】:2022-02-03 16:27:25
【问题描述】:
我经历了许多堆栈溢出问题,但没有一个有效。
找到网址并点击在新标签页中打开
假设我有这个字符串:这是 google url 点击它:www.google.com。在网站上而不是直接显示此字符串,我想从字符串中查找 url 并将其视为可点击的 url。
像这样:这是谷歌网址点击它:https://www.google.com/
我尝试过的是:
linkify("this is google url click on it : https://www.google.com/");
linkify = inputText => {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
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).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText;
};
此代码是堆栈溢出问题之一的和平。
这段代码的结果是:
this is google url click on it : <a href="https://www.google.com/" target="_blank"> https://www.google.com/ </a>
但我需要以这种方式进行最终输出:
这是谷歌网址点击它:https://www.google.com/
我尝试了 anchorme.js,但得到了相同的输出。
实现anchorme.js的步骤
import anchorme from 'anchorme';
anchorme("this is google url click on it : https://www.google.com/");
但输出相同。然后尝试链接 reactJs 包 this 但它是返回对象和崩溃应用程序。
**linkify 实现 **
import Linkify from 'react-linkify';
<Linkify>this is google url click on it : https://www.google.com/ </Linkify>
它的输出是带有道具、钥匙等键的大对象。
【问题讨论】:
-
你如何使用
linkify? -
@dfsq 我尝试使用 linkify 但它是返回对象。如果你能提供例子,那会很有帮助。
-
你需要发布你的代码示例,然后很容易修复它
-
@dfsq 在链接实现上添加代码
标签: javascript reactjs hyperlink