🔍Regex Recipes

File Extension Whitelist

Validate file extensions against a whitelist of allowed types.

Pattern

\.(jpg|jpeg|png|gif|webp)$

Explanation

Matches files ending with specified extensions. Example shows image files. Customize list for your needs.

Examples

JPG file
Input
photo.jpg
Output
✓ Match
PNG file
Input
screenshot.png
Output
✓ Match
Case sensitive
Input
IMAGE.JPG
Output
✗ No match (use i flag)
Not allowed
Input
document.pdf
Output
✗ No match

Code Examples

JavaScript
// Image files
const imageExtRegex = /\.(jpg|jpeg|png|gif|webp|svg)$/i;

// Document files
const docExtRegex = /\.(pdf|doc|docx|txt|md)$/i;

// Code files
const codeExtRegex = /\.(js|ts|jsx|tsx|py|java|cpp)$/i;

function isValidExtension(filename, allowedPattern) {
  return allowedPattern.test(filename.toLowerCase());
}

// Extract extension
function getExtension(filename) {
  return filename.slice(filename.lastIndexOf('.'));
}

Try it Now

💡 Tips

  • Add i flag for case-insensitive matching
  • Anchor with $ to match end of string
  • Combine with MIME type validation
  • Common groups: images, documents, code, video, audio

⚠️ Common Pitfalls

  • Use case-insensitive flag (i) for flexibility
  • Does not validate actual file content
  • Users can rename malicious files
  • Check MIME type on server side too