const regex = /(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?:<img|(?<!^)\\G)\\h*([-\\w]+)="([^"]+)"(?=.*?\\\/>)', 'gm')
const str = `<p>List of sample images.</p>
<img src="https://placehold.it/250x100.jpg" width="250" height="100" alt="Dimensions Set" />
<img src="https://placehold.it/250x100/99cc00/000.jpg?text=JPG" alt="JPG" /><br>
<img src="https://placehold.it/250x100.gif?text=GIF" alt="GIF" /><br>
<img src="https://placehold.it/250x100/ff6600/000.png?text=PNG" alt="PNG" /><br>
<img class="no-ext" src="https://placehold.it/350x150?text=No Extension" alt="No Ext" /><br>
<img src="https://placehold.it/250x100.png" custom-attr="custom1" another-attr="custom2" /><br>
<img class="svg" src="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg" alt="SVG" /><br>
<img class="webp" src="https://gstatic.com/webp/gallery/1.webp" width="100" alt="webP" /><br>`;
// 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