Hi Friends 👋,

Welcome To Infinitbility! ❤️

To validate file extension string using regex, use /\.[0-9a-z]+$/i it will handle all type file extension.

Let’s see short example of javascript regex for validate file extension.

const regex = /\.[0-9a-z]+$/i;
console.log(regex.test("infinitbility.exe"))

Today, I’m going to show you How do I check value contain valid date in javascript, as above mentioned, I’m going to use the above-mentioned regex with test() method.

Let’s start today’s tutorial how do you check valid file extension format in javascript using regex?

Here, I will show validate file extension in javascript and typescript.

Javascript regex for validate file extension example

Here, we will create common validate function where we will validate param should validate file extension.

function validate(param){
  const regex = /\.[0-9a-z]+$/i;
  return regex.test(param);
}

// validate exe file
console.log(validate("infinitbility.exe"))
// true

// validate image file
console.log(validate("image.jpg"))
// true

// validate file without extension
console.log(validate("infinitbility"))
// false

// validate file extension without dot
console.log(validate("[email protected]"))
// false

Output

Typescript regex for validate file extension example

Same like javascript, we will create a function and call it with diffrent parameters.

function validate(param: string){
  const regex = /\.[0-9a-z]+$/i;
  return regex.test(param);
}

// validate exe file
console.log(validate("infinitbility.exe"))
// true

// validate image file
console.log(validate("image.jpg"))
// true

// validate file without extension
console.log(validate("infinitbility"))
// false

// validate file extension without dot
console.log(validate("[email protected]"))
// false

Output

I hope it helps you, All the best 👍.