Reputation: 844
I want to replace various patterns in a text by using regular expressions. I am currently differentiating "normal" links, images and YouTube videos:
image link -> < img src="link" >
yt -> < iframe href="link" >
website link -> < a href="link" >
I am using the following regex patterns:
var image_reg = /(http:\/\/|https:\/\/).*(gif|jpg|jpeg|tiff|png)/ig;
var yt_reg = /(https:\/\/youtu.be\/|https:\/\/www.youtube.com\/watch\?v=)\S*/ig;
var url_reg = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)(?!\")/ig;
I need to find a way how to make sure that a link is not an image or a YT video when being matched as a normal link.
I am currently using the following, imperfect solution: I start with the image regex, followed by the YT regex. After that I run the link regex and replace every url that doesn't end with a " sign (and therefore is not a link inside the iframe or img tag)
However this is very risky and ugly. What is a better way to achieve my goal?
Upvotes: 0
Views: 63
Reputation: 3541
You can globally search for all links only and, in the callback of replace method, check if the link is youtube link/image to decide how to process it.
Upvotes: 1