首页 > 解决方案 > 在 reactJs/javascript 中查找 url 并使其可点击

问题描述

我经历了许多堆栈溢出问题,但没有一个有效。

查找 URL,然后单击在新选项卡中打开

假设我有这个字符串: 这是 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 打包,但它是返回对象和崩溃应用程序。

**链接实现**

import Linkify from 'react-linkify';

<Linkify>this is google url click on it : https://www.google.com/ </Linkify>

它的输出是带有道具、钥匙等键的大对象。

标签: javascriptreactjshyperlink

解决方案


使用linkify找到了解决方案。

import Linkify from 'react-linkify';

 <Linkify properties={{ target: '_blank', style: { color: 'blue' } }}>{message}/Linkify>

推荐阅读