Get file extension from name – Javascript, PHP

Getting file extension from file name or path can be done in Javascript and PHP. I will show you the steps to get the file extension and you can apply them in any language you want.

Following code will get the file extension from file name or file path in Javascript:

const path = "https://adnan-tech.com/wp-content/uploads/2024/07/Manage-google-account.png"

const parts = path.split(".")

const extension = parts[parts.length - 1].toLowerCase()

console.log(extension)

Your parts variable will look like this:

Array split explode - Javascript, PHP
Array split explode – Javascript, PHP

Following code will get the file extension from file name or path in PHP:

$path = "https://adnan-tech.com/wp-content/uploads/2024/07/Manage-google-account.png";

$parts = explode(".", $path);

$extension = $parts[count($parts) - 1];

$extension = strtolower($extension);

echo $extension;

We are converting the extension to lower-case because it will be helpful when you want to perform some action based on file extension. For example:

if (extension == "jpg") {
    // do something if file is JPEG
}

Some files has their extension in upper-case and some in lower-case. So it would be good if you convert that to lower-case to check properly.

That’s how you can get the file extension from it’s name or path using Javascript and PHP.