不包含"images"的字符串中的 URL 的正则表达式



我正在尝试创建一个针对字符串中URL的正则表达式。有两种类型的网址;图片网址和非图片网址。我希望两者都在一个正则表达式中,如下所示:(图像|非图像(。

我的正则表达式知识还不是很广泛。

字符串如下所示:

const string = "This is a piece of text that contains https://imagecdn.com/image/1.png. It also contains https://imagecdn.com/image/1.jpg and last https://twitter.com"

我希望能够替换所有网址,使其位于 html 标签中(如果是图像(,如果它是非图像 URL,则替换标签。

尝试下面的代码片段:

var p = "This is a piece of text that contains https://imagecdn.com/image/1.png. It also contains https://imagecdn.com/image/1.jpg and last https://twitter.com"
var regex = /((http(s)?(://))+(www.)?([w-./])*(.[a-zA-Z]{2,3}/?))[^sbn|]*[^.,;:?!@^$ -]/gi;
var replaced = p.replace(regex, (matched) => {
  if (matched.includes('twitter')) {
    return `<a>${matched}</a>`
  }
  
  return `<img src=${matched}/>`
})
console.log(replaced);

最新更新