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

How to Extract File Extensions with JavaScript?

Linda Hamilton
Release: 2024-11-09 13:58:02
Original
334 people have browsed it

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>
<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">/*TODO*/
Copy after login

}

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();
    Copy after login

    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;
    Copy after login

    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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template