Open In App

How to trim a file extension from string using JavaScript ?

Given a fileName in string format and the task is to trim the file extension from the string using JavaScript.

Example 1: This example gets the file Name by using split(), slice() and join() methods.




<!DOCTYPE HTML> 
<html
    <head
        <title
            Trim a file extension from a
            string using JavaScript
        </title>
    </head
      
    <body style = "text-align:center;"
      
        <h1 style = "color:green;"
            GeeksForGeeks 
        </h1>
  
        <p id = "GFG_UP" style
            "font-size: 15px; font-weight: bold;">
        </p>
          
        <button onclick = "gfg_Run()"
            click here
        </button>
          
        <p id = "GFG_DOWN" style
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script>
            var el_up = document.getElementById("GFG_UP");
            var el_down = document.getElementById("GFG_DOWN");
            var fName = "fileName.jpg";
            el_up.innerHTML = "String = '"+fName + "'";
          
            function gfg_Run() {
                el_down.innerHTML = fName.split('.').slice(0, -1).join('.');
            }         
        </script
    </body
</html>                    

Output:

Example 2: This example gets the file Name by using RegExp along with replace() method.




<!DOCTYPE HTML> 
<html
    <head
        <title>
            Trim a file extension from a
            string using JavaScript
        </title>
    </head
      
    <body style = "text-align:center;"
      
        <h1 style = "color:green;"
            GeeksForGeeks 
        </h1>
  
        <p id = "GFG_UP" style
            "font-size: 15px; font-weight: bold;">
        </p>
          
        <button onclick = "gfg_Run()"
            click here
        </button>
          
        <p id = "GFG_DOWN" style =
            "color:green; font-size: 20px; font-weight: bold;">
        </p>
          
        <script>
            var el_up = document.getElementById("GFG_UP");
            var el_down = document.getElementById("GFG_DOWN");
            var fName = "fileName.jpg";
            el_up.innerHTML = "String = '" + fName + "'";
          
            function gfg_Run() {
                el_down.innerHTML =fName.replace(/\.[^/.]+$/, "")
            }         
        </script
    </body
</html>                    

Output:


Article Tags :