const regex = /(?:'|")([^"':]*?\.(?:png|jpe?g|gif)[^'"]*(?=[^<]+?>))/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:\'|")([^"\':]*?\\.(?:png|jpe?g|gif)[^\'"]*(?=[^<]+?>))', 'g')
const str = `TO MATCH:
<img src="images/vendor.png" alt="" > <img src="images/vendor.gif" class="box-bg-image" alt="" >
<img src="images/vendor-dp-20141009-flatware.jpg" class="box-bg-image" alt="" >
<img src="images/vendor-flatware.jpeg" class="box" alt="" >
<img src='images/vendor-flatware.jpeg' class="box" >
<img alt="" src= 'images/vendor-flatware.jpeg' alt="" >
<img src=' images/vendor-flatware.jpg' alt="" >
<img src=' images/vendor-flatware.gif' alt="" >
<img src=' images/vendor-flatware.png ' alt="" >
<img src='../silverware.png' alt="" >
<img class="box" src='images/vendor-watch.png' alt="" >
<img src=" images/vendor-flatware.jpeg " alt="" >
< img src="images/vendor-flatware.jpeg " alt="" >
< img src="images/vendor-flatware.jpeg " alt="" >
<img src="vendor.gif" alt="">
NOT TO MATCH:
<img src="http://thirdpartycdn.com/image.jpg">
<img src='http://thirdpartycdn.com/image.png'>
<img src="http://thirdpartycdn.com/image.gif" class="box-bg-image" alt="">
img src="images/vendor-flatware.jpeg "
<img src="images/vendorpng" alt="" >`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions