55

I need a regular expression to validate image file extensions in javascript. Do you have one ?

2

1 Answer 1

167

Could you explain the purpose?

Anyway here's one assuming you support few image types.

(/\.(gif|jpe?g|tiff?|png|webp|bmp)$/i).test(filename)

I have put the whole regular expression within parentheses () so as to disambiguate between the slash (/) operator and RegExp object. See JSLint for more details.

Here's the raw regex as well.

/\.(gif|jpe?g|tiff?|png|webp|bmp)$/i

This Regex also assumes that you're including the dot before the extension. Remove the \. if you're not.

Sign up to request clarification or add additional context in comments.

5 Comments

Instead of jpg|jpeg you can do: jpe?g
How about adding webp to this list?
Could we consider .ico as na image ?
How would this look like when you also want to include capitalised extensions? And thank you for your answer
@Woww the /i part makes it case insensitive, i.e. include capitalised

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.