w3resource

JavaScript: Get the extension of a filename

JavaScript Basic: Exercise-14 with Solution

Write a JavaScript exercise to get the filename extension.

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.



Follow us on Facebook and Twitter for latest update.