logo hsb.horse
← Back to snippets index

Snippets

Image Extension Regex

JavaScript/TypeScript regex pattern to detect image formats from filenames. Supports png, webp, jpg, jpeg, avif, gif.

Published: Updated:

There are many scenarios where you want to determine whether a file is an image, such as file uploads or path processing. Cover major image formats with a simple regex.

Code

const REGEX_IMG = /\.(png|webp|jpe?g|avif|gif)/;
function isImage(filename: string): boolean {
return REGEX_IMG.test(filename);
}

Usage Examples

isImage("photo.jpg"); // true
isImage("image.jpeg"); // true (e? covers jpeg as well)
isImage("graphic.png"); // true
isImage("animation.gif"); // true
isImage("compressed.webp"); // true
isImage("modern.avif"); // true
isImage("document.pdf"); // false

Pattern Explanation

  • \.: Matches a literal dot
  • (png|webp|jpe?g|avif|gif): Alternation via capture group
    • jpe?g: Matches both jpg and jpeg (e is optional)

Case-Insensitive Matching

To handle uppercase extensions, add the i flag:

const REGEX_IMG = /\.(png|webp|jpe?g|avif|gif)/i;
isImage("PHOTO.JPG"); // true

Alternative Approaches

If you prefer MIME types over regex:

async function isImageFile(file: File): Promise<boolean> {
return file.type.startsWith("image/");
}

When extracting extensions from URLs, the URL API is more robust:

function getExtension(url: string): string {
try {
const pathname = new URL(url).pathname;
return pathname.slice(pathname.lastIndexOf("."));
} catch {
return "";
}
}

While regex is simple, it may produce false positives when URLs contain query parameters. Choose the appropriate method based on your use case.