Sling Academy
Home/JavaScript/JavaScript: Get filename & file extension from a URL

JavaScript: Get filename & file extension from a URL

Last updated: March 23, 2023

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!

Next Article: How to Generate Random Colors in JavaScript (4 Approaches)

Previous Article: JavaScript: Remove Multiple Consecutive White Spaces

Series: JavaScript Strings

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration