Dha*_*val 3 javascript hyperlink reactjs
我遇到了很多堆栈溢出问题,但没有一个有效。
找到网址并单击在新选项卡中打开
假设我有这个字符串: 这是谷歌网址,点击它: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;
};
Run Code Online (Sandbox Code Playgroud)
这段代码是堆栈溢出问题之一的和平。
这段代码的结果是:
this is google url click on it : <a href="https://www.google.com/" target="_blank"> https://www.google.com/ </a>
Run Code Online (Sandbox Code Playgroud)
但我需要以这种方式最终输出:
这是谷歌网址,点击它: https: //www.google.com/
我尝试过anchorme.js但得到了相同的输出。
实施anchorme.js的步骤
import anchorme from 'anchorme';
anchorme("this is google url click on it : https://www.google.com/");
Run Code Online (Sandbox Code Playgroud)
但输出是相同的。然后尝试 linkify reactJs 打包它,但它返回对象并导致应用程序崩溃。
**链接实现**
import Linkify from 'react-linkify';
<Linkify>this is google url click on it : https://www.google.com/ </Linkify>
Run Code Online (Sandbox Code Playgroud)
它的输出是带有诸如 props、keys 等键的大对象。
使用 Linkify-react 使链接可点击 使用以下语法以您的格式自定义链接
const componentDecorator = (href, text, key) => (
<a className="linkify__text" href={href} key={key} target="_blank">
{text}
</a>
);
<Linkify componentDecorator={componentDecorator}>
....
</Linkify>
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5795 次 |
| 最近记录: |