簡體   English   中英

不包含“圖片”的字符串中網址的正則表達式

[英]Regex for URL within string that doesn't contain “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"

我希望能夠將所有url替換為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}\\/?))[^\\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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM