Currently i'm building a function for a messaging system that detects a url from the string and add anchor tag to it. But i need to exclude the urls that points to images and documents. The function that i created now detects all the urls and add anchor tag to it but it adds anchor tag to images and documents also.
i tried these regex but no desired result
/(.[^>"]|[^=]")\b(https?|ftp|file)/gi
/(https?:\/\/[^\s]+)/g
function urlParsing(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
})
}
console.log(urlParsing('Hello john https://stackoverflow.com'));
console.log(urlParsing('Hello john https://picsum.photos/200/300.jpg'));
Add a negative lookahead to your regex. This is the (?!) group, and it means match as long as whatever comes before isn't followed by anything in the lookahead. Then add a check to test the text against that parser and return from the function if the test fails.
function urlParsing(text) {
var urlRegex = /(https?:\/\/(?!.*\.(jpg|png|gif|pdf|docx))[^\s]+)/g;
if(!urlRegex.test(text)) {return false};
return text.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
})
}
console.log(urlParsing('Hello john https://stackoverflow.com'));
console.log(urlParsing('Hello john https://pbs.org'));
console.log(urlParsing('Hello john https://picsum.photos/200/300.jpg'));
console.log(urlParsing('Hello john https://picsum.photos/200/300.jpg?arg=x&arg2=y'));
console.log(urlParsing('Hello john https://picsum.photos/200/300.png'));
console.log(urlParsing('Hello john https://picsum.photos/200/300.gif'));
console.log(urlParsing('Hello john https://picsum.photos/200/300.pdf'));
console.log(urlParsing('Hello john https://picsum.photos/200/300.docx'));