Regex - return only first src url match

70 Views Asked by At

I'm trying to extract the first jpg from a page of text. multiple paragraphs and multiple urls in each, but i only want the first url/jpg, stop after first is matched/returned.

sample page;

this is some text and a url src="https://www.someurl.jpg" more text, more text, more text. more text, more text

more text, more text. this is some text and a url src="https://www.anotherurl.jpg" more text, more text, more text. more text, more text.

Current Code;

(?<=src=")(.*?)(?=")

This code returns both urls. I need the output to be just the first one it finds and stop there, just return the first.

Output required;

https://www.someurl.jpg

any help appreciated.

1

There are 1 best solutions below

2
Bujaq On

Your regex is quite good, just add surroundings and g flag. /(?<=src=")(.*?)(?=")/g Now You gave correct regex.

console.log(`I'm trying to extract the first jpg from a page of text. multiple paragraphs and multiple urls in each, but i only want the first url/jpg, stop after first is matched/returned.

sample page;

this is some text and a url src="https://www.so23123123123l.jpg" more text, more text, more text. more text, more text

more text, more text. this is some text and a url src="https://www.anotherurl.jpg" more text, more text, more text. more text, more text.`.match(/(?<=src=")(.*?)(?=")/ig));

You can read here about regexp flags.