我正在尝试创建一个针对字符串内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"
我希望能够将所有url替换为html标签(如果它是图片),并将其替换为非图片URL。
答案 0 :(得分:0)
尝试以下代码段:
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}\/?))[^\s\b\n|]*[^.,;:\?\!\@\^\$ -]/gi;
var replaced = p.replace(regex, (matched) => {
if (matched.includes('twitter')) {
return `<a>${matched}</a>`
}
return `<img src=${matched}/>`
})
console.log(replaced);