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"); // trueisImage("image.jpeg"); // true (e? covers jpeg as well)isImage("graphic.png"); // trueisImage("animation.gif"); // trueisImage("compressed.webp"); // trueisImage("modern.avif"); // trueisImage("document.pdf"); // falsePattern Explanation
\.: Matches a literal dot(png|webp|jpe?g|avif|gif): Alternation via capture groupjpe?g: Matches bothjpgandjpeg(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"); // trueAlternative 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.
hsb.horse