javascript - 在 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>
它的输出是带有道具、钥匙等键的大对象。
解决方案
使用linkify找到了解决方案。
import Linkify from 'react-linkify';
<Linkify properties={{ target: '_blank', style: { color: 'blue' } }}>{message}/Linkify>
推荐阅读
- r - 如何使用反应数据在闪亮的应用程序中更改 flexdashbord::gauge 的标签?
- javascript - 在 React 中使用 Firestore 不起作用 - 找不到模块
- html - 刷新浏览器后浏览器忽略表单的第一个文本字段?
- r - 在 R 中读取 Excel 文件并提取特定颜色单元格
- python - 如何用移动相机在几帧之间画直线?
- android - 文件路径存在总是返回 false Android Above Q
- php - PHP 对反转 DatePeriod 迭代器的困惑
- mysql - 来自域类的 Hibernate 自动表生成在 Grails 和 MySQL 中不起作用
- r - 堆积面积图中不显示彩色堆积区域
- spring-boot - 如何实现 CQRS 以及在哪里创建读取数据库