首页 > 解决方案 > 正则表达式 - 检查字符串是否包含部分 URL 并转换为链接

问题描述

我只是无法理解正则表达式,这让我发疯。

我有以下字符串;

'This is a random string of text with a link to google.com/test and another link to facebook.com`

我想要做的是google.com/test变成https://google.com/test但将facebook.com链接保留为纯文本。

所以基本上,google.com(包括前缀)的任何实例都会变成一个链接,但任何其他 URL 都将保留为纯文本。

有人可以给我一个正确的方向吗?

标签: javascriptregex

解决方案


简单replace()会做:

var str = 'This is a random string of text with a link to google.com/test and another link to facebook.com';
str = str.replace('google.com/test', 'https://google.com/test');
console.log(str);


推荐阅读