Home  >  Article  >  Web Front-end  >  How to Extract File Extensions with JavaScript?

How to Extract File Extensions with JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-09 13:58:02277browse

How to Extract File Extensions with JavaScript?

How do I Get File Extensions with JavaScript?

Problem:

Consider the following code:

var file1 = "50.xsl";<br>var file2 = "30.doc";<br>getFileExtension(file1); //returns xsl<br>getFileExtension(file2); //returns doc</p>
<p>function getFileExtension(filename) {</p>
<pre class="brush:php;toolbar:false">/*TODO*/

}

Question:

Complete the getFileExtension function to extract and return the file extension (e.g., xsl, doc).

Answer:

There are multiple ways to accomplish this:

  1. Using .split and .pop:

    return filename.split('.').pop();

    This splits the filename into an array using the . delimiter and returns the last element (the extension).

  2. Using a Regular Expression:

    return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;

    This regular expression starts by checking if the filename contains a period (.). If so, it then matches and returns the extension using a negative lookahead (prevents matching the period) and a $ (end of string) anchor.

    Note: If the filename does not contain a period (indicating no extension), it returns undefined to avoid returning an empty string.

The above is the detailed content of How to Extract File Extensions with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn