Extracting File Extensions in JavaScript
JavaScript lacks built-in functionality for retrieving file extensions, making it necessary to create a custom function. The provided code presents a solution that accurately extracts the extension for both file1 and file2.
Function Implementation:
The getFileExtension function accepts a filename as its argument and separates the extension using a period (.) as the delimiter. The final element of the resulting array is the file extension.
Revised Code:
The revised version of the code incorporating the suggested enhancements:
function getFileExtension(filename) { return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined; }
This version ensures that both files with and without extensions are handled correctly. If the filename does not contain a period, the function returns undefined.
The above is the detailed content of How to Extract File Extensions in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!