Home > Article > Web Front-end > How to Extract File Extensions from Filenames in JavaScript?
Getting File Extensions with JavaScript
This article discusses extracting file extensions from filenames using JavaScript. For example, obtaining "xsl" from "50.xsl" or "doc" from "30.doc."
Function Implementation:
To achieve this, implement the getFileExtension function with the filename as an argument.
Answer:
Numerous methods can be employed to retrieve file extensions. One straightforward approach is:
return filename.split('.').pop();
This code splits the filename at the dot, and takes the last element of the resultant array.
Another method utilizes regular expressions:
return /[^.]+$/.exec(filename);
This regex matches the characters after the last dot in the filename.
To handle cases where the file may not have an extension, we can modify the second method as follows:
return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
This verifies if the filename contains a dot before attempting to extract the extension, returning undefined if no extension is found.
The above is the detailed content of How to Extract File Extensions from Filenames in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!