JavaScript: Get filename & file extension from a URL

Updated: March 23, 2023 By: Khue Post a comment

This short and straightforward article will walk you through a couple of different ways to extract the name and the extension from a URL of a file. All of these approaches will only use vanilla JavaScript. No third-party libraries are required.

Using the split() method

The point here is to use the split() method to split the URL string by the forward slash “/” delimiter. Next, access the last item in the resulting array to get the file name. Use the split() method again to split the file name by the period “.” delimiter. Access the last item in the resulting array to get the file extension.

Example:

// a URL to a photo
const url = 'https://www.slingacademy.com/some-path/sample-photo.jpg';

// Split the URL by "/" and get the last element using spread operator
const [...parts] = url.split('/');

// get the filename
const fileName = parts.pop(); 

// Split the file name by "."
const [...segments] = fileName.split('.');

// get the file extension
const fileExtension = segments.pop(); 

// get the name of the file without extension
const fileNameWithoutExtension = segments.join('.');

// Log them to the console
console.log("File Name:", fileName);
console.log("File Name Without Extension:", fileNameWithoutExtension);
console.log("File Extension:", fileExtension);

Output:

File Name: sample-photo.jpg
File Name Without Extension: sample-photo
File Extension: jpg

Using regular expressions

You can also use regular expressions to get the filename and file extension from a given URL. The pattern we will use is:

/([^\\/]+)\\. ([^\\/]+)$/i

Example:

// sample URL
const url = 'https://www.slingacademy.com/some-path/my-file.zip';

// The regex to match file name and extension
const regex = /([^\/]+)\.([^\/]+)$/i;

// Apply the regex to the URL
const match = url.match(regex);

// Check if there is a match
if (match) {
  // Get the file name from the first capture group
  const filemaWithoutExtension = match[1];

  // Get the file extension from the second capture group
  const fileExtension = match[2];

  // filemname with extension
  const fileName = filemaWithoutExtension + '.' + fileExtension;

  // Log the file name and extension
  console.log('File name:', fileName);
  console.log('File name without extension:', filemaWithoutExtension)
  console.log('File extension:', fileExtension);
} else {
  // No match found
  console.log('No file name or extension found');
}

Output:

File name: my-file.zip
script.js:23 File name without extension: my-file
script.js:24 File extension: zip

You can find more information about regular expressions in this cheat sheet: JavaScript Regular Expressions Cheat Sheet.

Happy coding & have a nice day!