JAVASCRIPT

Extract All Image Source URLs from HTML

Quickly extract all `src` attribute values from `<img>` tags within an HTML string using a regular expression in JavaScript.

function extractImageSrcs(htmlString) {
  const srcRegex = /<img[^>]*src\s*=\s*['"]([^'"]*)['"][^>]*>/gi;
  let matches;
  const srcs = [];

  while ((matches = srcRegex.exec(htmlString)) !== null) {
    // The captured group 1 contains the src URL
    srcs.push(matches[1]);
  }
  return srcs;
}

// Example:
// const html = '<p>Some text</p><img src="image1.jpg" alt="Alt 1"><p>More text</p><img data-src="lazy.png" src="image2.png"><img src="/assets/img/logo.svg" class="logo">';
// console.log(extractImageSrcs(html));
// Expected: ['image1.jpg', 'image2.png', '/assets/img/logo.svg']
How it works: The `extractImageSrcs` function uses a regular expression to find all `<img>` tags and extract their `src` attribute values. The regex `/<img[^>]*src\s*=\s*['"]([^'"]*)['"][^>]*>/gi` captures the content within the single or double quotes of the `src` attribute. It uses the global (`g`) flag to find all occurrences and the case-insensitive (`i`) flag. The `while` loop with `exec()` iterates through all matches, pushing the captured `src` URLs into an array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs