w3resource

JavaScript: Get the extension of a filename

JavaScript Basic: Exercise-14 with Solution

Get File Extension of Filename

Write a JavaScript exercise to get the filename extension.

This JavaScript exercise involves extracting the file extension from a given filename. It typically requires identifying the position of the last dot in the filename and then extracting the substring that follows it, which represents the file extension. Regular expressions or string manipulation methods like split() or substring() are commonly used to achieve this task.

Visual Presentation:

JavaScript: Get the extension of a filename

Sample Solution:

JavaScript Code:

// Assign the string "system.php" to the variable filename
filename = "system.php";

// Log the result of extracting the file extension using split and pop to the console
console.log(filename.split('.').pop());

// Reassign the variable filename to the string "abc.js"
filename = "abc.js";

// Log the result of extracting the file extension using split and pop to the console
console.log(filename.split('.').pop()); 

Output:

php
js

Live Demo:

See the Pen JavaScript: Extension of a filename - basic-ex-14 by w3resource (@w3resource) on CodePen.


ES6 Version:

// Using ES6 const to declare the variable filename and log the file extension
let filename = "system.php";
console.log(filename.split('.').pop());

// Reassign the variable filename and log the file extension for the new value
filename = "abc.js";
console.log(filename.split('.').pop());

Improve this sample solution and post your code through Disqus.

Previous: JavaScript exercise to create a variable using a user-defined name.
Next: JavaScript program to get the difference between a given number and 13, if the number is greater than 13 return double the absolute difference.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-basic-exercise-14.php