Home >Web Front-end >JS Tutorial >How to delete the extension and get the file name by clicking on JavaScript
In the previous article "Two methods for JavaScript to obtain the keys of an associative array", I introduced how to obtain the keys of an associative array in JavaScript. Interested friends can learn about it~
The focus of this article is to teach you how to click to delete the extension and get the file name through JavaScript.
Without further ado, let’s get straight to the point!
Let me introduce you to two implementation methods:
The code for the first method is as follows:
Note: This example uses The split()
, slice()
and join()
methods get the file name.
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:#ff311f;" > PHP中文网 </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> 点击 </button> <p id = "GFG_DOWN" style = "color:#ff311f; 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>
The effect is as follows:
split() method: used to split a string into characters string array.
slice() method: Extracts a certain part of the string and returns the extracted part as a new string.
join() method: used to put all elements in the array into a string.
The second method code is as follows:
Note: This example uses RegExp
and replace()
method gets the file name.
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body style = "text-align:center;"> <h1 style = "color:#17c4ff;" > PHP中文网 </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> 点击 </button> <p id = "GFG_DOWN" style = "color:#17c4ff; 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>
The effect is as follows:
RegExp is the abbreviation of regular expression. The RegExp object is used to specify the content to be retrieved in the text. The RegExp object can be defined through the new keyword.
Thereplace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
Finally, I would like to recommend "JavaScript Basics Tutorial" ~ Welcome everyone to learn ~
The above is the detailed content of How to delete the extension and get the file name by clicking on JavaScript. For more information, please follow other related articles on the PHP Chinese website!