Tuesday, June 29, 2021

Junior Developer Central JS Practice Exercise - 02

 
Question: 

Write a Javascript program to get the extension of a filename. 





Answer: 

function fileNameExt (str) {

let extFileName = str.slice(str.lastIndexOf('.'));

return extFileName;

}




> declare a function 'fileNameExt' 
> it has one parameter 'str' 
> we declare a variable 'extFileName' 
> it is initialized with a value when we use some basic string methods to get our output
> our program should extract the extension of a filename and return just that
>> like this: fileNameExt ('index.html') should return '.html'
> so first we use the slice function to slice the input and return the last portion of the string 
> in order for the slice function to work, we need to pass in a start index number and an end index number (optional)
> since we do not know what the filename is, we cannot be sure of a specific index number
> the one thing we are sure of is that the extension name of a file is always followed by a dot
> however we do not know as to what type of file it is as it can have two dots as well 
>> like this: webpack.config.js
> in the above example we have a file name that has two dots
> so we use the lastIndexOf method to find the last occurence of the dot in the filename
> we enter the lastIndexOf - 'dot' as the start number we want to pass, in the slice method
> this will slice our input string and return the entire portion following the last dot in a filename
> we then return the variable 'extFileName'

No comments:

Post a Comment