How to trim a file extension from a String in JavaScript?












220















For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).



I saw x.substring(0, x.indexOf('.jpg')) on DZone Snippets, but wouldn't x.substring(0, x.length-4) perform better? Because, length is a property and doesn't do character checking whereas indexOf() is a function and does character checking.










share|improve this question

























  • See: Regular expression to remove a file's extension and see also: How can i get file extensions with javascript?

    – Shog9
    Nov 22 '10 at 21:28











  • Pretty much the same as stackoverflow.com/questions/1991608/…. And unless you do one heck of a lot of these, worrying about efficiency is Premature Optimisation.

    – The Archetypal Paul
    Nov 22 '10 at 21:28













  • In the age of ES6, also see the Path module – in case you are using nodejs or a proper transpilation

    – Frank Nocke
    Jul 2 '17 at 19:04


















220















For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).



I saw x.substring(0, x.indexOf('.jpg')) on DZone Snippets, but wouldn't x.substring(0, x.length-4) perform better? Because, length is a property and doesn't do character checking whereas indexOf() is a function and does character checking.










share|improve this question

























  • See: Regular expression to remove a file's extension and see also: How can i get file extensions with javascript?

    – Shog9
    Nov 22 '10 at 21:28











  • Pretty much the same as stackoverflow.com/questions/1991608/…. And unless you do one heck of a lot of these, worrying about efficiency is Premature Optimisation.

    – The Archetypal Paul
    Nov 22 '10 at 21:28













  • In the age of ES6, also see the Path module – in case you are using nodejs or a proper transpilation

    – Frank Nocke
    Jul 2 '17 at 19:04
















220












220








220


34






For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).



I saw x.substring(0, x.indexOf('.jpg')) on DZone Snippets, but wouldn't x.substring(0, x.length-4) perform better? Because, length is a property and doesn't do character checking whereas indexOf() is a function and does character checking.










share|improve this question
















For example, assuming that x = filename.jpg, I want to get filename, where filename could be any file name (Let's assume the file name only contains [a-zA-Z0-9-_] to simplify.).



I saw x.substring(0, x.indexOf('.jpg')) on DZone Snippets, but wouldn't x.substring(0, x.length-4) perform better? Because, length is a property and doesn't do character checking whereas indexOf() is a function and does character checking.







javascript replace substring substr indexof






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Feb 11 '16 at 16:11









T J

32.7k956110




32.7k956110










asked Nov 22 '10 at 21:24









ma11hew28ma11hew28

55.7k92368551




55.7k92368551













  • See: Regular expression to remove a file's extension and see also: How can i get file extensions with javascript?

    – Shog9
    Nov 22 '10 at 21:28











  • Pretty much the same as stackoverflow.com/questions/1991608/…. And unless you do one heck of a lot of these, worrying about efficiency is Premature Optimisation.

    – The Archetypal Paul
    Nov 22 '10 at 21:28













  • In the age of ES6, also see the Path module – in case you are using nodejs or a proper transpilation

    – Frank Nocke
    Jul 2 '17 at 19:04





















  • See: Regular expression to remove a file's extension and see also: How can i get file extensions with javascript?

    – Shog9
    Nov 22 '10 at 21:28











  • Pretty much the same as stackoverflow.com/questions/1991608/…. And unless you do one heck of a lot of these, worrying about efficiency is Premature Optimisation.

    – The Archetypal Paul
    Nov 22 '10 at 21:28













  • In the age of ES6, also see the Path module – in case you are using nodejs or a proper transpilation

    – Frank Nocke
    Jul 2 '17 at 19:04



















See: Regular expression to remove a file's extension and see also: How can i get file extensions with javascript?

– Shog9
Nov 22 '10 at 21:28





See: Regular expression to remove a file's extension and see also: How can i get file extensions with javascript?

– Shog9
Nov 22 '10 at 21:28













Pretty much the same as stackoverflow.com/questions/1991608/…. And unless you do one heck of a lot of these, worrying about efficiency is Premature Optimisation.

– The Archetypal Paul
Nov 22 '10 at 21:28







Pretty much the same as stackoverflow.com/questions/1991608/…. And unless you do one heck of a lot of these, worrying about efficiency is Premature Optimisation.

– The Archetypal Paul
Nov 22 '10 at 21:28















In the age of ES6, also see the Path module – in case you are using nodejs or a proper transpilation

– Frank Nocke
Jul 2 '17 at 19:04







In the age of ES6, also see the Path module – in case you are using nodejs or a proper transpilation

– Frank Nocke
Jul 2 '17 at 19:04














24 Answers
24






active

oldest

votes


















108














If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).



If you don't know the length @John Hartsock regex would be the right approach.



If you'd rather not use regular expressions, you can try this (less performant):



filename.split('.').slice(0, -1).join('.')


Note that it will fail on files without extension.






share|improve this answer


























  • I like this solution the best. It's clean, and I can use it cause I know the file extension is always .jpg. I was looking for something like Ruby's x[0..-5], and x.slice(0, -4) looks great! Thanks! And thank you to everyone else for all the other robust alternatives provided!

    – ma11hew28
    Nov 23 '10 at 6:12






  • 13





    this is not the optimal solution, please check other solutions below.

    – bunjeeb
    Apr 6 '15 at 23:02






  • 8





    And if you're not 100% sure about the length of the extension, then don't this: "picture.jpeg".slice(0, -4) -> "picture."

    – basic6
    Apr 7 '15 at 9:37






  • 12





    This is dangerous solution, cause you don't really know the length of the format.

    – Coder
    Mar 13 '17 at 18:47











  • ma11hew28, but what if it's .jpeg instead of .jpg?

    – tomJO
    May 10 '18 at 8:55



















375














Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg or .html



x.replace(/.[^/.]+$/, "")





share|improve this answer





















  • 13





    You probably want to also disallow / as a path separator, so the regexp is /.[^/.]+$/

    – gsnedders
    Nov 22 '10 at 21:35






  • 7





    This should be the right answer

    – Vik
    Apr 23 '15 at 1:31











  • This works for any length of file extension (.txt or .html or .htaccess) and also allows for the file name to contain additional period (.) characters. It wouldn't handle eg .tar.gz due to the extension itself containing a period. It's more common for a file name to contain additional periods than a file extension. Thanks!

    – Steve Seeger
    Jan 28 '16 at 20:56











  • @Vik There's a difference between the 'right answer' and the accepted answer. An accepted answer is just the answer that was helpful for the one who asked the question.

    – Steven
    Nov 13 '17 at 14:37








  • 2





    I suppose that there may be issues with the Windows platform because there can be back slashes. So the regexp should be /.[^/\.]+$/.

    – Alex Chuev
    Dec 18 '17 at 13:32





















135














In node.js, the name of the file without the extension can be obtained as follows.



const path = require('path');
var filename = 'hello.html';

path.parse(filename).name; // hello
path.parse(filename).ext; // .html


Further explanation at Node.js documentation page.






share|improve this answer





















  • 1





    What you are talking about @kaasdude.... this method effectively removes the extension on node., not sure what you wanted to express, but this method works pearls.

    – Erick
    Sep 23 '18 at 22:00



















107














x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?



EDIT:



To answer... sure, if you always have an extension of .jpg, x.length-4 would work just fine.



However, if you don't know the length of your extension, any of a number of solutions are better/more robust.



x = x.replace(/..+$/, '');



OR



x = x.substring(0, x.lastIndexOf('.'));



OR



x = x.replace(/(.*).(.*?)$/, "$1");



OR (with the assumption filename only has one dot)



parts = x.match(/[^.]+/);
x = parts[0];


OR (also with only one dot)



parts = x.split(".");
x = parts[0];





share|improve this answer





















  • 2





    +1 for the split idea

    – basarat
    May 10 '13 at 1:47






  • 10





    ?? You can have a filename ex: "summer.family.jpg" in that case split('.')[0] will return only a partial file name. I would remove that one from the answer, or clearly state underneath the issue for that example. @basarat ...

    – Roko C. Buljan
    Oct 2 '13 at 22:19











  • Something I do frequently regarding part splits: var parts = full_file.split("."); var ext = parts[parts.length-1]; var file = parts.splice(0,parts.length-1).join(".");

    – radicand
    Oct 3 '13 at 20:41











  • x.split(".") should not even be considered an answer. I know I use a '.' in almost all of my file naming conventions, i.e. 'survey.controller.js', or 'my.family.jpg'.

    – Lee Brindley
    Feb 17 '16 at 16:52











  • @Lee2808: Hence the warning of only one dot. This is simply meant to show that there are a number of approaches, depending on the application. I would certainly use one of the other methods in almost all cases.

    – Jeff B
    Feb 17 '16 at 17:57



















36














You can perhaps use the assumption that the last dot will be the extension delimiter.



var x = 'filename.jpg';
var f = x.substr(0, x.lastIndexOf('.'));


If file has no extension, it will return empty string. To fix that use this function



function removeExtension(filename){
var lastDotPosition = filename.lastIndexOf(".");
if (lastDotPosition === -1) return filename;
else return filename.substr(0, lastDotPosition);
}





share|improve this answer


























  • Warning, this fails if there happens to be no filename extension. You're left with an empty string.

    – Brad
    Dec 1 '13 at 4:33






  • 14





    Shorter version that accounts for no dots. var f = x.substr(0, x.lastIndexOf('.')) || x; This works because an empty string is falsy, therefore it returns x.

    – Jonathan Rowny
    May 6 '15 at 4:38



















13














In Node.js versions prior to 0.12.x:



path.basename(filename, path.extname(filename))



Of course this also works in 0.12.x and later.






share|improve this answer































    11














    This works, even when the delimiter is not present in the string.



    String.prototype.beforeLastIndex = function (delimiter) {
    return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
    }

    "image".beforeLastIndex(".") // "image"
    "image.jpeg".beforeLastIndex(".") // "image"
    "image.second.jpeg".beforeLastIndex(".") // "image.second"
    "image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"


    Can also be used as a one-liner like this:



    var filename = "this.is.a.filename.txt";
    console.log(filename.split(".").slice(0,-1).join(".") || filename + "");


    EDIT: This is a more efficient solution:



    String.prototype.beforeLastIndex = function (delimiter) {
    return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
    }





    share|improve this answer

































      8














      I like this one because it is a one liner which isn't too hard to read:



      filename.substring(0, filename.lastIndexOf('.')) || filename





      share|improve this answer































        7














        Another one-liner:



        x.split(".").slice(0, -1).join(".")





        share|improve this answer































          6














          Here's another regex-based solution:



          filename.replace(/.[^.$]+$/, '');


          This should only chop off the last segment.






          share|improve this answer































            6














            I don't know if it's a valid option but I use this:



            name = filename.split(".");
            // trimming with pop()
            name.pop();
            // getting the name with join()
            name.join(''); // empty string since default separator is ', '


            It's not just one operation I know, but at least it should always work!






            share|improve this answer


























            • very elegant and working!

              – danfromisrael
              Jun 26 '16 at 16:21






            • 1





              It should not be name.join('') but name.join('.'). You split by dot but join by comma, so hello.name.txt returns hello, name

              – Evil
              Nov 1 '17 at 9:20



















            5














            Simple one:



            var n = str.lastIndexOf(".");
            return n > -1 ? str.substr(0, n) : str;





            share|improve this answer































              4














              The accepted answer strips the last extension part only (.jpeg), which might be a good choice in most cases.



              I once had to strip all extensions (.tar.gz) and the file names were restricted to not contain dots (so 2015-01-01.backup.tar would not be a problem):



              var name = "2015-01-01_backup.tar.gz";
              name.replace(/(.[^/.]+)+$/, "");





              share|improve this answer































                3














                If you have to process a variable that contains the complete path (ex.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") and you want to return just "filename" you can use:



                theName = thePath.split("/").slice(-1).join().split(".").shift();


                the result will be theName == "filename";



                To try it write the following command into the console window of your chrome debugger:
                window.location.pathname.split("/").slice(-1).join().split(".").shift()



                If you have to process just the file name and its extension (ex.: theNameWithExt = "filename.jpg"):



                theName = theNameWithExt.split(".").shift();


                the result will be theName == "filename", the same as above;



                Notes:




                1. The first one is a little bit slower cause performes more
                  operations; but works in both cases, in other words it can extract
                  the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.

                2. Both solutions work for both local and server files;


                But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.



                working snippet 1: the complete path




                var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
                theName = thePath.split("/").slice(-1).join().split(".").shift();
                alert(theName);

                  





                working snippet 2: the file name with extension




                var theNameWithExt = "filename.jpg";
                theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                alert(theName);

                  





                working snippet 2: the file name with double extension




                var theNameWithExt = "filename.tar.gz";
                theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                alert(theName);

                  








                share|improve this answer

































                  3














                  This can also be done easily with path using the basename and extname methods.



                  const path = require('path')

                  path.basename('test.txt', path.extname('test.txt'))





                  share|improve this answer

































                    2














                    var fileName = "something.extension";
                    fileName.slice(0, -path.extname(fileName).length) // === "something"





                    share|improve this answer































                      2














                      Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-



                      path.replace(path.substr(path.lastIndexOf('.')), '')






                      share|improve this answer































                        0














                        This is where regular expressions come in handy! Javascript's .replace() method will take a regular expression, and you can utilize that to accomplish what you want:



                        // assuming var x = filename.jpg or some extension
                        x = x.replace(/(.*).[^.]+$/, "$1");





                        share|improve this answer



















                        • 2





                          Regex is too heavy and unreadable for such simple task

                          – Tomas
                          Jun 4 '14 at 11:13



















                        0














                        Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';



                            yourStr = yourStr.slice(0, -4); // 'test'





                        share|improve this answer































                          0














                          You can use path to maneuver.



                          var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
                          var MYEXT = '.js';
                          var fileName = path.basename(MYPATH, MYEXT);
                          var filePath = path.dirname(MYPATH) + '/' + fileName;


                          Output



                          > filePath
                          '/User/HELLO/WORLD/FILENAME'
                          > fileName
                          'FILENAME'
                          > MYPATH
                          '/User/HELLO/WORLD/FILENAME.js'





                          share|improve this answer































                            0














                            x.slice(0, -(x.split('.').pop().length + 1));





                            share|improve this answer































                              0














                              This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.



                              It works for:




                              • files without an extension: "myletter"

                              • files with '.' in the name: "my.letter.txt"

                              • unknown length of file extension: "my.letter.html"


                              Here's the code:



                              var filename = "my.letter.txt" // some filename

                              var substrings = filename.split('.'); // split the string at '.'
                              if (substrings.length == 1)
                              {
                              return filename; // there was no file extension, file was something like 'myfile'
                              }
                              else
                              {
                              var ext = substrings.pop(); // remove the last element
                              var name = substrings.join(""); // rejoin the remaining elements without separator
                              name = ([name, ext]).join("."); // readd the extension
                              return name;
                              }





                              share|improve this answer


























                              • fails with hello.tar.gz, output is hellotar.

                                – Asif Ali
                                Nov 27 '17 at 6:51











                              • #AsifAli thanks you are right, I forgot to readd the file extension. I've updated the answer, I hope it works now.

                                – Little Brain
                                Nov 27 '17 at 13:15



















                              -1














                              First you have to get correct the extension of file then you can remove it



                              try this code



                              <!DOCTYPE html>
                              <html>
                              <body>
                              <p>Click the button to display the array values after the split.</p>
                              <button onclick="myFunction()">Try it</button>
                              <p id="demo"></p>
                              <script>
                              function getFileName(str){
                              var res = str.split('.').pop();
                              alert('filename: ' + str.replace('.' + res, ''));
                              alert('extension: ' +res);
                              }
                              function myFunction() {
                              getFileName('abc.jpg');
                              getFileName('abc.def.jpg');
                              getFileName('abc.def.ghi.jpg');
                              getFileName('abc.def.ghi.123.jpg');
                              getFileName('abc.def.ghi.123.456.jpg');
                              getFileName('abc.jpg.xyz.jpg'); // test with Sébastien comment lol
                              }
                              </script>
                              </body>
                              </html>





                              share|improve this answer


























                              • Try this: getFileName('abc.jpg.xyz.jpg');

                                – Sébastien
                                Dec 13 '18 at 10:32











                              • file name is: 'abc.jpg.xyz', extension is: '.jpg' so what??

                                – VnDevil
                                Dec 15 '18 at 7:36











                              • No, the file name will be 'abc.xyz' as both '.jpg' will be replaced by ''.

                                – Sébastien
                                Dec 15 '18 at 11:47











                              • so you should not named file by that way

                                – VnDevil
                                Jan 17 at 3:04











                              • No, a function should work for every input, the user shouldn't be restricted in its input, at least in this case. The extension of a file is always the last part, so only the last part should used, once and only once.

                                – Sébastien
                                Jan 19 at 11:47



















                              -2














                              I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.






                              share|improve this answer



















                              • 2





                                "If you're going for performance, don't go for javascript at all" - What else are you suggesting to use in web applications..?

                                – T J
                                Feb 11 '16 at 16:15











                              • He doesn't mention web applications.

                                – Lucas Moeskops
                                Mar 22 '17 at 22:01






                              • 1





                                This question was asked and answer was posted in 2010, 7 years ago, and JavaScript was pretty much used only in web applications. (Node was just born, it didn't even had a guide or NPM at that time)

                                – T J
                                Mar 23 '17 at 9:16













                              • ;-) Still, if performance matters on tasks like this, you might consider doing this on the backend and process the results on the frontend.

                                – Lucas Moeskops
                                Mar 23 '17 at 10:23













                              Your Answer






                              StackExchange.ifUsing("editor", function () {
                              StackExchange.using("externalEditor", function () {
                              StackExchange.using("snippets", function () {
                              StackExchange.snippets.init();
                              });
                              });
                              }, "code-snippets");

                              StackExchange.ready(function() {
                              var channelOptions = {
                              tags: "".split(" "),
                              id: "1"
                              };
                              initTagRenderer("".split(" "), "".split(" "), channelOptions);

                              StackExchange.using("externalEditor", function() {
                              // Have to fire editor after snippets, if snippets enabled
                              if (StackExchange.settings.snippets.snippetsEnabled) {
                              StackExchange.using("snippets", function() {
                              createEditor();
                              });
                              }
                              else {
                              createEditor();
                              }
                              });

                              function createEditor() {
                              StackExchange.prepareEditor({
                              heartbeatType: 'answer',
                              autoActivateHeartbeat: false,
                              convertImagesToLinks: true,
                              noModals: true,
                              showLowRepImageUploadWarning: true,
                              reputationToPostImages: 10,
                              bindNavPrevention: true,
                              postfix: "",
                              imageUploader: {
                              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                              allowUrls: true
                              },
                              onDemand: true,
                              discardSelector: ".discard-answer"
                              ,immediatelyShowMarkdownHelp:true
                              });


                              }
                              });














                              draft saved

                              draft discarded


















                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4250364%2fhow-to-trim-a-file-extension-from-a-string-in-javascript%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown

























                              24 Answers
                              24






                              active

                              oldest

                              votes








                              24 Answers
                              24






                              active

                              oldest

                              votes









                              active

                              oldest

                              votes






                              active

                              oldest

                              votes









                              108














                              If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).



                              If you don't know the length @John Hartsock regex would be the right approach.



                              If you'd rather not use regular expressions, you can try this (less performant):



                              filename.split('.').slice(0, -1).join('.')


                              Note that it will fail on files without extension.






                              share|improve this answer


























                              • I like this solution the best. It's clean, and I can use it cause I know the file extension is always .jpg. I was looking for something like Ruby's x[0..-5], and x.slice(0, -4) looks great! Thanks! And thank you to everyone else for all the other robust alternatives provided!

                                – ma11hew28
                                Nov 23 '10 at 6:12






                              • 13





                                this is not the optimal solution, please check other solutions below.

                                – bunjeeb
                                Apr 6 '15 at 23:02






                              • 8





                                And if you're not 100% sure about the length of the extension, then don't this: "picture.jpeg".slice(0, -4) -> "picture."

                                – basic6
                                Apr 7 '15 at 9:37






                              • 12





                                This is dangerous solution, cause you don't really know the length of the format.

                                – Coder
                                Mar 13 '17 at 18:47











                              • ma11hew28, but what if it's .jpeg instead of .jpg?

                                – tomJO
                                May 10 '18 at 8:55
















                              108














                              If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).



                              If you don't know the length @John Hartsock regex would be the right approach.



                              If you'd rather not use regular expressions, you can try this (less performant):



                              filename.split('.').slice(0, -1).join('.')


                              Note that it will fail on files without extension.






                              share|improve this answer


























                              • I like this solution the best. It's clean, and I can use it cause I know the file extension is always .jpg. I was looking for something like Ruby's x[0..-5], and x.slice(0, -4) looks great! Thanks! And thank you to everyone else for all the other robust alternatives provided!

                                – ma11hew28
                                Nov 23 '10 at 6:12






                              • 13





                                this is not the optimal solution, please check other solutions below.

                                – bunjeeb
                                Apr 6 '15 at 23:02






                              • 8





                                And if you're not 100% sure about the length of the extension, then don't this: "picture.jpeg".slice(0, -4) -> "picture."

                                – basic6
                                Apr 7 '15 at 9:37






                              • 12





                                This is dangerous solution, cause you don't really know the length of the format.

                                – Coder
                                Mar 13 '17 at 18:47











                              • ma11hew28, but what if it's .jpeg instead of .jpg?

                                – tomJO
                                May 10 '18 at 8:55














                              108












                              108








                              108







                              If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).



                              If you don't know the length @John Hartsock regex would be the right approach.



                              If you'd rather not use regular expressions, you can try this (less performant):



                              filename.split('.').slice(0, -1).join('.')


                              Note that it will fail on files without extension.






                              share|improve this answer















                              If you know the length of the extension, you can use x.slice(0, -4) (where 4 is the three characters of the extension and the dot).



                              If you don't know the length @John Hartsock regex would be the right approach.



                              If you'd rather not use regular expressions, you can try this (less performant):



                              filename.split('.').slice(0, -1).join('.')


                              Note that it will fail on files without extension.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jul 13 '18 at 14:08









                              slezica

                              43.5k1675133




                              43.5k1675133










                              answered Nov 22 '10 at 21:29









                              Marek SapotaMarek Sapota

                              14.2k32642




                              14.2k32642













                              • I like this solution the best. It's clean, and I can use it cause I know the file extension is always .jpg. I was looking for something like Ruby's x[0..-5], and x.slice(0, -4) looks great! Thanks! And thank you to everyone else for all the other robust alternatives provided!

                                – ma11hew28
                                Nov 23 '10 at 6:12






                              • 13





                                this is not the optimal solution, please check other solutions below.

                                – bunjeeb
                                Apr 6 '15 at 23:02






                              • 8





                                And if you're not 100% sure about the length of the extension, then don't this: "picture.jpeg".slice(0, -4) -> "picture."

                                – basic6
                                Apr 7 '15 at 9:37






                              • 12





                                This is dangerous solution, cause you don't really know the length of the format.

                                – Coder
                                Mar 13 '17 at 18:47











                              • ma11hew28, but what if it's .jpeg instead of .jpg?

                                – tomJO
                                May 10 '18 at 8:55



















                              • I like this solution the best. It's clean, and I can use it cause I know the file extension is always .jpg. I was looking for something like Ruby's x[0..-5], and x.slice(0, -4) looks great! Thanks! And thank you to everyone else for all the other robust alternatives provided!

                                – ma11hew28
                                Nov 23 '10 at 6:12






                              • 13





                                this is not the optimal solution, please check other solutions below.

                                – bunjeeb
                                Apr 6 '15 at 23:02






                              • 8





                                And if you're not 100% sure about the length of the extension, then don't this: "picture.jpeg".slice(0, -4) -> "picture."

                                – basic6
                                Apr 7 '15 at 9:37






                              • 12





                                This is dangerous solution, cause you don't really know the length of the format.

                                – Coder
                                Mar 13 '17 at 18:47











                              • ma11hew28, but what if it's .jpeg instead of .jpg?

                                – tomJO
                                May 10 '18 at 8:55

















                              I like this solution the best. It's clean, and I can use it cause I know the file extension is always .jpg. I was looking for something like Ruby's x[0..-5], and x.slice(0, -4) looks great! Thanks! And thank you to everyone else for all the other robust alternatives provided!

                              – ma11hew28
                              Nov 23 '10 at 6:12





                              I like this solution the best. It's clean, and I can use it cause I know the file extension is always .jpg. I was looking for something like Ruby's x[0..-5], and x.slice(0, -4) looks great! Thanks! And thank you to everyone else for all the other robust alternatives provided!

                              – ma11hew28
                              Nov 23 '10 at 6:12




                              13




                              13





                              this is not the optimal solution, please check other solutions below.

                              – bunjeeb
                              Apr 6 '15 at 23:02





                              this is not the optimal solution, please check other solutions below.

                              – bunjeeb
                              Apr 6 '15 at 23:02




                              8




                              8





                              And if you're not 100% sure about the length of the extension, then don't this: "picture.jpeg".slice(0, -4) -> "picture."

                              – basic6
                              Apr 7 '15 at 9:37





                              And if you're not 100% sure about the length of the extension, then don't this: "picture.jpeg".slice(0, -4) -> "picture."

                              – basic6
                              Apr 7 '15 at 9:37




                              12




                              12





                              This is dangerous solution, cause you don't really know the length of the format.

                              – Coder
                              Mar 13 '17 at 18:47





                              This is dangerous solution, cause you don't really know the length of the format.

                              – Coder
                              Mar 13 '17 at 18:47













                              ma11hew28, but what if it's .jpeg instead of .jpg?

                              – tomJO
                              May 10 '18 at 8:55





                              ma11hew28, but what if it's .jpeg instead of .jpg?

                              – tomJO
                              May 10 '18 at 8:55













                              375














                              Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg or .html



                              x.replace(/.[^/.]+$/, "")





                              share|improve this answer





















                              • 13





                                You probably want to also disallow / as a path separator, so the regexp is /.[^/.]+$/

                                – gsnedders
                                Nov 22 '10 at 21:35






                              • 7





                                This should be the right answer

                                – Vik
                                Apr 23 '15 at 1:31











                              • This works for any length of file extension (.txt or .html or .htaccess) and also allows for the file name to contain additional period (.) characters. It wouldn't handle eg .tar.gz due to the extension itself containing a period. It's more common for a file name to contain additional periods than a file extension. Thanks!

                                – Steve Seeger
                                Jan 28 '16 at 20:56











                              • @Vik There's a difference between the 'right answer' and the accepted answer. An accepted answer is just the answer that was helpful for the one who asked the question.

                                – Steven
                                Nov 13 '17 at 14:37








                              • 2





                                I suppose that there may be issues with the Windows platform because there can be back slashes. So the regexp should be /.[^/\.]+$/.

                                – Alex Chuev
                                Dec 18 '17 at 13:32


















                              375














                              Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg or .html



                              x.replace(/.[^/.]+$/, "")





                              share|improve this answer





















                              • 13





                                You probably want to also disallow / as a path separator, so the regexp is /.[^/.]+$/

                                – gsnedders
                                Nov 22 '10 at 21:35






                              • 7





                                This should be the right answer

                                – Vik
                                Apr 23 '15 at 1:31











                              • This works for any length of file extension (.txt or .html or .htaccess) and also allows for the file name to contain additional period (.) characters. It wouldn't handle eg .tar.gz due to the extension itself containing a period. It's more common for a file name to contain additional periods than a file extension. Thanks!

                                – Steve Seeger
                                Jan 28 '16 at 20:56











                              • @Vik There's a difference between the 'right answer' and the accepted answer. An accepted answer is just the answer that was helpful for the one who asked the question.

                                – Steven
                                Nov 13 '17 at 14:37








                              • 2





                                I suppose that there may be issues with the Windows platform because there can be back slashes. So the regexp should be /.[^/\.]+$/.

                                – Alex Chuev
                                Dec 18 '17 at 13:32
















                              375












                              375








                              375







                              Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg or .html



                              x.replace(/.[^/.]+$/, "")





                              share|improve this answer















                              Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg or .html



                              x.replace(/.[^/.]+$/, "")






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Apr 21 '16 at 15:47









                              Mosh Feu

                              15.5k105081




                              15.5k105081










                              answered Nov 22 '10 at 21:29









                              John HartsockJohn Hartsock

                              65.2k19111138




                              65.2k19111138








                              • 13





                                You probably want to also disallow / as a path separator, so the regexp is /.[^/.]+$/

                                – gsnedders
                                Nov 22 '10 at 21:35






                              • 7





                                This should be the right answer

                                – Vik
                                Apr 23 '15 at 1:31











                              • This works for any length of file extension (.txt or .html or .htaccess) and also allows for the file name to contain additional period (.) characters. It wouldn't handle eg .tar.gz due to the extension itself containing a period. It's more common for a file name to contain additional periods than a file extension. Thanks!

                                – Steve Seeger
                                Jan 28 '16 at 20:56











                              • @Vik There's a difference between the 'right answer' and the accepted answer. An accepted answer is just the answer that was helpful for the one who asked the question.

                                – Steven
                                Nov 13 '17 at 14:37








                              • 2





                                I suppose that there may be issues with the Windows platform because there can be back slashes. So the regexp should be /.[^/\.]+$/.

                                – Alex Chuev
                                Dec 18 '17 at 13:32
















                              • 13





                                You probably want to also disallow / as a path separator, so the regexp is /.[^/.]+$/

                                – gsnedders
                                Nov 22 '10 at 21:35






                              • 7





                                This should be the right answer

                                – Vik
                                Apr 23 '15 at 1:31











                              • This works for any length of file extension (.txt or .html or .htaccess) and also allows for the file name to contain additional period (.) characters. It wouldn't handle eg .tar.gz due to the extension itself containing a period. It's more common for a file name to contain additional periods than a file extension. Thanks!

                                – Steve Seeger
                                Jan 28 '16 at 20:56











                              • @Vik There's a difference between the 'right answer' and the accepted answer. An accepted answer is just the answer that was helpful for the one who asked the question.

                                – Steven
                                Nov 13 '17 at 14:37








                              • 2





                                I suppose that there may be issues with the Windows platform because there can be back slashes. So the regexp should be /.[^/\.]+$/.

                                – Alex Chuev
                                Dec 18 '17 at 13:32










                              13




                              13





                              You probably want to also disallow / as a path separator, so the regexp is /.[^/.]+$/

                              – gsnedders
                              Nov 22 '10 at 21:35





                              You probably want to also disallow / as a path separator, so the regexp is /.[^/.]+$/

                              – gsnedders
                              Nov 22 '10 at 21:35




                              7




                              7





                              This should be the right answer

                              – Vik
                              Apr 23 '15 at 1:31





                              This should be the right answer

                              – Vik
                              Apr 23 '15 at 1:31













                              This works for any length of file extension (.txt or .html or .htaccess) and also allows for the file name to contain additional period (.) characters. It wouldn't handle eg .tar.gz due to the extension itself containing a period. It's more common for a file name to contain additional periods than a file extension. Thanks!

                              – Steve Seeger
                              Jan 28 '16 at 20:56





                              This works for any length of file extension (.txt or .html or .htaccess) and also allows for the file name to contain additional period (.) characters. It wouldn't handle eg .tar.gz due to the extension itself containing a period. It's more common for a file name to contain additional periods than a file extension. Thanks!

                              – Steve Seeger
                              Jan 28 '16 at 20:56













                              @Vik There's a difference between the 'right answer' and the accepted answer. An accepted answer is just the answer that was helpful for the one who asked the question.

                              – Steven
                              Nov 13 '17 at 14:37







                              @Vik There's a difference between the 'right answer' and the accepted answer. An accepted answer is just the answer that was helpful for the one who asked the question.

                              – Steven
                              Nov 13 '17 at 14:37






                              2




                              2





                              I suppose that there may be issues with the Windows platform because there can be back slashes. So the regexp should be /.[^/\.]+$/.

                              – Alex Chuev
                              Dec 18 '17 at 13:32







                              I suppose that there may be issues with the Windows platform because there can be back slashes. So the regexp should be /.[^/\.]+$/.

                              – Alex Chuev
                              Dec 18 '17 at 13:32













                              135














                              In node.js, the name of the file without the extension can be obtained as follows.



                              const path = require('path');
                              var filename = 'hello.html';

                              path.parse(filename).name; // hello
                              path.parse(filename).ext; // .html


                              Further explanation at Node.js documentation page.






                              share|improve this answer





















                              • 1





                                What you are talking about @kaasdude.... this method effectively removes the extension on node., not sure what you wanted to express, but this method works pearls.

                                – Erick
                                Sep 23 '18 at 22:00
















                              135














                              In node.js, the name of the file without the extension can be obtained as follows.



                              const path = require('path');
                              var filename = 'hello.html';

                              path.parse(filename).name; // hello
                              path.parse(filename).ext; // .html


                              Further explanation at Node.js documentation page.






                              share|improve this answer





















                              • 1





                                What you are talking about @kaasdude.... this method effectively removes the extension on node., not sure what you wanted to express, but this method works pearls.

                                – Erick
                                Sep 23 '18 at 22:00














                              135












                              135








                              135







                              In node.js, the name of the file without the extension can be obtained as follows.



                              const path = require('path');
                              var filename = 'hello.html';

                              path.parse(filename).name; // hello
                              path.parse(filename).ext; // .html


                              Further explanation at Node.js documentation page.






                              share|improve this answer















                              In node.js, the name of the file without the extension can be obtained as follows.



                              const path = require('path');
                              var filename = 'hello.html';

                              path.parse(filename).name; // hello
                              path.parse(filename).ext; // .html


                              Further explanation at Node.js documentation page.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Apr 13 '18 at 14:06

























                              answered Jul 24 '15 at 16:43









                              Jibesh PatraJibesh Patra

                              1,48411011




                              1,48411011








                              • 1





                                What you are talking about @kaasdude.... this method effectively removes the extension on node., not sure what you wanted to express, but this method works pearls.

                                – Erick
                                Sep 23 '18 at 22:00














                              • 1





                                What you are talking about @kaasdude.... this method effectively removes the extension on node., not sure what you wanted to express, but this method works pearls.

                                – Erick
                                Sep 23 '18 at 22:00








                              1




                              1





                              What you are talking about @kaasdude.... this method effectively removes the extension on node., not sure what you wanted to express, but this method works pearls.

                              – Erick
                              Sep 23 '18 at 22:00





                              What you are talking about @kaasdude.... this method effectively removes the extension on node., not sure what you wanted to express, but this method works pearls.

                              – Erick
                              Sep 23 '18 at 22:00











                              107














                              x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?



                              EDIT:



                              To answer... sure, if you always have an extension of .jpg, x.length-4 would work just fine.



                              However, if you don't know the length of your extension, any of a number of solutions are better/more robust.



                              x = x.replace(/..+$/, '');



                              OR



                              x = x.substring(0, x.lastIndexOf('.'));



                              OR



                              x = x.replace(/(.*).(.*?)$/, "$1");



                              OR (with the assumption filename only has one dot)



                              parts = x.match(/[^.]+/);
                              x = parts[0];


                              OR (also with only one dot)



                              parts = x.split(".");
                              x = parts[0];





                              share|improve this answer





















                              • 2





                                +1 for the split idea

                                – basarat
                                May 10 '13 at 1:47






                              • 10





                                ?? You can have a filename ex: "summer.family.jpg" in that case split('.')[0] will return only a partial file name. I would remove that one from the answer, or clearly state underneath the issue for that example. @basarat ...

                                – Roko C. Buljan
                                Oct 2 '13 at 22:19











                              • Something I do frequently regarding part splits: var parts = full_file.split("."); var ext = parts[parts.length-1]; var file = parts.splice(0,parts.length-1).join(".");

                                – radicand
                                Oct 3 '13 at 20:41











                              • x.split(".") should not even be considered an answer. I know I use a '.' in almost all of my file naming conventions, i.e. 'survey.controller.js', or 'my.family.jpg'.

                                – Lee Brindley
                                Feb 17 '16 at 16:52











                              • @Lee2808: Hence the warning of only one dot. This is simply meant to show that there are a number of approaches, depending on the application. I would certainly use one of the other methods in almost all cases.

                                – Jeff B
                                Feb 17 '16 at 17:57
















                              107














                              x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?



                              EDIT:



                              To answer... sure, if you always have an extension of .jpg, x.length-4 would work just fine.



                              However, if you don't know the length of your extension, any of a number of solutions are better/more robust.



                              x = x.replace(/..+$/, '');



                              OR



                              x = x.substring(0, x.lastIndexOf('.'));



                              OR



                              x = x.replace(/(.*).(.*?)$/, "$1");



                              OR (with the assumption filename only has one dot)



                              parts = x.match(/[^.]+/);
                              x = parts[0];


                              OR (also with only one dot)



                              parts = x.split(".");
                              x = parts[0];





                              share|improve this answer





















                              • 2





                                +1 for the split idea

                                – basarat
                                May 10 '13 at 1:47






                              • 10





                                ?? You can have a filename ex: "summer.family.jpg" in that case split('.')[0] will return only a partial file name. I would remove that one from the answer, or clearly state underneath the issue for that example. @basarat ...

                                – Roko C. Buljan
                                Oct 2 '13 at 22:19











                              • Something I do frequently regarding part splits: var parts = full_file.split("."); var ext = parts[parts.length-1]; var file = parts.splice(0,parts.length-1).join(".");

                                – radicand
                                Oct 3 '13 at 20:41











                              • x.split(".") should not even be considered an answer. I know I use a '.' in almost all of my file naming conventions, i.e. 'survey.controller.js', or 'my.family.jpg'.

                                – Lee Brindley
                                Feb 17 '16 at 16:52











                              • @Lee2808: Hence the warning of only one dot. This is simply meant to show that there are a number of approaches, depending on the application. I would certainly use one of the other methods in almost all cases.

                                – Jeff B
                                Feb 17 '16 at 17:57














                              107












                              107








                              107







                              x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?



                              EDIT:



                              To answer... sure, if you always have an extension of .jpg, x.length-4 would work just fine.



                              However, if you don't know the length of your extension, any of a number of solutions are better/more robust.



                              x = x.replace(/..+$/, '');



                              OR



                              x = x.substring(0, x.lastIndexOf('.'));



                              OR



                              x = x.replace(/(.*).(.*?)$/, "$1");



                              OR (with the assumption filename only has one dot)



                              parts = x.match(/[^.]+/);
                              x = parts[0];


                              OR (also with only one dot)



                              parts = x.split(".");
                              x = parts[0];





                              share|improve this answer















                              x.length-4 only accounts for extensions of 3 characters. What if you have filename.jpegor filename.pl?



                              EDIT:



                              To answer... sure, if you always have an extension of .jpg, x.length-4 would work just fine.



                              However, if you don't know the length of your extension, any of a number of solutions are better/more robust.



                              x = x.replace(/..+$/, '');



                              OR



                              x = x.substring(0, x.lastIndexOf('.'));



                              OR



                              x = x.replace(/(.*).(.*?)$/, "$1");



                              OR (with the assumption filename only has one dot)



                              parts = x.match(/[^.]+/);
                              x = parts[0];


                              OR (also with only one dot)



                              parts = x.split(".");
                              x = parts[0];






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Apr 21 '17 at 20:51

























                              answered Nov 22 '10 at 21:28









                              Jeff BJeff B

                              27.3k55481




                              27.3k55481








                              • 2





                                +1 for the split idea

                                – basarat
                                May 10 '13 at 1:47






                              • 10





                                ?? You can have a filename ex: "summer.family.jpg" in that case split('.')[0] will return only a partial file name. I would remove that one from the answer, or clearly state underneath the issue for that example. @basarat ...

                                – Roko C. Buljan
                                Oct 2 '13 at 22:19











                              • Something I do frequently regarding part splits: var parts = full_file.split("."); var ext = parts[parts.length-1]; var file = parts.splice(0,parts.length-1).join(".");

                                – radicand
                                Oct 3 '13 at 20:41











                              • x.split(".") should not even be considered an answer. I know I use a '.' in almost all of my file naming conventions, i.e. 'survey.controller.js', or 'my.family.jpg'.

                                – Lee Brindley
                                Feb 17 '16 at 16:52











                              • @Lee2808: Hence the warning of only one dot. This is simply meant to show that there are a number of approaches, depending on the application. I would certainly use one of the other methods in almost all cases.

                                – Jeff B
                                Feb 17 '16 at 17:57














                              • 2





                                +1 for the split idea

                                – basarat
                                May 10 '13 at 1:47






                              • 10





                                ?? You can have a filename ex: "summer.family.jpg" in that case split('.')[0] will return only a partial file name. I would remove that one from the answer, or clearly state underneath the issue for that example. @basarat ...

                                – Roko C. Buljan
                                Oct 2 '13 at 22:19











                              • Something I do frequently regarding part splits: var parts = full_file.split("."); var ext = parts[parts.length-1]; var file = parts.splice(0,parts.length-1).join(".");

                                – radicand
                                Oct 3 '13 at 20:41











                              • x.split(".") should not even be considered an answer. I know I use a '.' in almost all of my file naming conventions, i.e. 'survey.controller.js', or 'my.family.jpg'.

                                – Lee Brindley
                                Feb 17 '16 at 16:52











                              • @Lee2808: Hence the warning of only one dot. This is simply meant to show that there are a number of approaches, depending on the application. I would certainly use one of the other methods in almost all cases.

                                – Jeff B
                                Feb 17 '16 at 17:57








                              2




                              2





                              +1 for the split idea

                              – basarat
                              May 10 '13 at 1:47





                              +1 for the split idea

                              – basarat
                              May 10 '13 at 1:47




                              10




                              10





                              ?? You can have a filename ex: "summer.family.jpg" in that case split('.')[0] will return only a partial file name. I would remove that one from the answer, or clearly state underneath the issue for that example. @basarat ...

                              – Roko C. Buljan
                              Oct 2 '13 at 22:19





                              ?? You can have a filename ex: "summer.family.jpg" in that case split('.')[0] will return only a partial file name. I would remove that one from the answer, or clearly state underneath the issue for that example. @basarat ...

                              – Roko C. Buljan
                              Oct 2 '13 at 22:19













                              Something I do frequently regarding part splits: var parts = full_file.split("."); var ext = parts[parts.length-1]; var file = parts.splice(0,parts.length-1).join(".");

                              – radicand
                              Oct 3 '13 at 20:41





                              Something I do frequently regarding part splits: var parts = full_file.split("."); var ext = parts[parts.length-1]; var file = parts.splice(0,parts.length-1).join(".");

                              – radicand
                              Oct 3 '13 at 20:41













                              x.split(".") should not even be considered an answer. I know I use a '.' in almost all of my file naming conventions, i.e. 'survey.controller.js', or 'my.family.jpg'.

                              – Lee Brindley
                              Feb 17 '16 at 16:52





                              x.split(".") should not even be considered an answer. I know I use a '.' in almost all of my file naming conventions, i.e. 'survey.controller.js', or 'my.family.jpg'.

                              – Lee Brindley
                              Feb 17 '16 at 16:52













                              @Lee2808: Hence the warning of only one dot. This is simply meant to show that there are a number of approaches, depending on the application. I would certainly use one of the other methods in almost all cases.

                              – Jeff B
                              Feb 17 '16 at 17:57





                              @Lee2808: Hence the warning of only one dot. This is simply meant to show that there are a number of approaches, depending on the application. I would certainly use one of the other methods in almost all cases.

                              – Jeff B
                              Feb 17 '16 at 17:57











                              36














                              You can perhaps use the assumption that the last dot will be the extension delimiter.



                              var x = 'filename.jpg';
                              var f = x.substr(0, x.lastIndexOf('.'));


                              If file has no extension, it will return empty string. To fix that use this function



                              function removeExtension(filename){
                              var lastDotPosition = filename.lastIndexOf(".");
                              if (lastDotPosition === -1) return filename;
                              else return filename.substr(0, lastDotPosition);
                              }





                              share|improve this answer


























                              • Warning, this fails if there happens to be no filename extension. You're left with an empty string.

                                – Brad
                                Dec 1 '13 at 4:33






                              • 14





                                Shorter version that accounts for no dots. var f = x.substr(0, x.lastIndexOf('.')) || x; This works because an empty string is falsy, therefore it returns x.

                                – Jonathan Rowny
                                May 6 '15 at 4:38
















                              36














                              You can perhaps use the assumption that the last dot will be the extension delimiter.



                              var x = 'filename.jpg';
                              var f = x.substr(0, x.lastIndexOf('.'));


                              If file has no extension, it will return empty string. To fix that use this function



                              function removeExtension(filename){
                              var lastDotPosition = filename.lastIndexOf(".");
                              if (lastDotPosition === -1) return filename;
                              else return filename.substr(0, lastDotPosition);
                              }





                              share|improve this answer


























                              • Warning, this fails if there happens to be no filename extension. You're left with an empty string.

                                – Brad
                                Dec 1 '13 at 4:33






                              • 14





                                Shorter version that accounts for no dots. var f = x.substr(0, x.lastIndexOf('.')) || x; This works because an empty string is falsy, therefore it returns x.

                                – Jonathan Rowny
                                May 6 '15 at 4:38














                              36












                              36








                              36







                              You can perhaps use the assumption that the last dot will be the extension delimiter.



                              var x = 'filename.jpg';
                              var f = x.substr(0, x.lastIndexOf('.'));


                              If file has no extension, it will return empty string. To fix that use this function



                              function removeExtension(filename){
                              var lastDotPosition = filename.lastIndexOf(".");
                              if (lastDotPosition === -1) return filename;
                              else return filename.substr(0, lastDotPosition);
                              }





                              share|improve this answer















                              You can perhaps use the assumption that the last dot will be the extension delimiter.



                              var x = 'filename.jpg';
                              var f = x.substr(0, x.lastIndexOf('.'));


                              If file has no extension, it will return empty string. To fix that use this function



                              function removeExtension(filename){
                              var lastDotPosition = filename.lastIndexOf(".");
                              if (lastDotPosition === -1) return filename;
                              else return filename.substr(0, lastDotPosition);
                              }






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jun 4 '14 at 11:12









                              Community

                              11




                              11










                              answered Nov 22 '10 at 21:30









                              Martin AlgestenMartin Algesten

                              8,94613469




                              8,94613469













                              • Warning, this fails if there happens to be no filename extension. You're left with an empty string.

                                – Brad
                                Dec 1 '13 at 4:33






                              • 14





                                Shorter version that accounts for no dots. var f = x.substr(0, x.lastIndexOf('.')) || x; This works because an empty string is falsy, therefore it returns x.

                                – Jonathan Rowny
                                May 6 '15 at 4:38



















                              • Warning, this fails if there happens to be no filename extension. You're left with an empty string.

                                – Brad
                                Dec 1 '13 at 4:33






                              • 14





                                Shorter version that accounts for no dots. var f = x.substr(0, x.lastIndexOf('.')) || x; This works because an empty string is falsy, therefore it returns x.

                                – Jonathan Rowny
                                May 6 '15 at 4:38

















                              Warning, this fails if there happens to be no filename extension. You're left with an empty string.

                              – Brad
                              Dec 1 '13 at 4:33





                              Warning, this fails if there happens to be no filename extension. You're left with an empty string.

                              – Brad
                              Dec 1 '13 at 4:33




                              14




                              14





                              Shorter version that accounts for no dots. var f = x.substr(0, x.lastIndexOf('.')) || x; This works because an empty string is falsy, therefore it returns x.

                              – Jonathan Rowny
                              May 6 '15 at 4:38





                              Shorter version that accounts for no dots. var f = x.substr(0, x.lastIndexOf('.')) || x; This works because an empty string is falsy, therefore it returns x.

                              – Jonathan Rowny
                              May 6 '15 at 4:38











                              13














                              In Node.js versions prior to 0.12.x:



                              path.basename(filename, path.extname(filename))



                              Of course this also works in 0.12.x and later.






                              share|improve this answer




























                                13














                                In Node.js versions prior to 0.12.x:



                                path.basename(filename, path.extname(filename))



                                Of course this also works in 0.12.x and later.






                                share|improve this answer


























                                  13












                                  13








                                  13







                                  In Node.js versions prior to 0.12.x:



                                  path.basename(filename, path.extname(filename))



                                  Of course this also works in 0.12.x and later.






                                  share|improve this answer













                                  In Node.js versions prior to 0.12.x:



                                  path.basename(filename, path.extname(filename))



                                  Of course this also works in 0.12.x and later.







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Dec 16 '15 at 0:01









                                  blah238blah238

                                  75121139




                                  75121139























                                      11














                                      This works, even when the delimiter is not present in the string.



                                      String.prototype.beforeLastIndex = function (delimiter) {
                                      return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
                                      }

                                      "image".beforeLastIndex(".") // "image"
                                      "image.jpeg".beforeLastIndex(".") // "image"
                                      "image.second.jpeg".beforeLastIndex(".") // "image.second"
                                      "image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"


                                      Can also be used as a one-liner like this:



                                      var filename = "this.is.a.filename.txt";
                                      console.log(filename.split(".").slice(0,-1).join(".") || filename + "");


                                      EDIT: This is a more efficient solution:



                                      String.prototype.beforeLastIndex = function (delimiter) {
                                      return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
                                      }





                                      share|improve this answer






























                                        11














                                        This works, even when the delimiter is not present in the string.



                                        String.prototype.beforeLastIndex = function (delimiter) {
                                        return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
                                        }

                                        "image".beforeLastIndex(".") // "image"
                                        "image.jpeg".beforeLastIndex(".") // "image"
                                        "image.second.jpeg".beforeLastIndex(".") // "image.second"
                                        "image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"


                                        Can also be used as a one-liner like this:



                                        var filename = "this.is.a.filename.txt";
                                        console.log(filename.split(".").slice(0,-1).join(".") || filename + "");


                                        EDIT: This is a more efficient solution:



                                        String.prototype.beforeLastIndex = function (delimiter) {
                                        return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
                                        }





                                        share|improve this answer




























                                          11












                                          11








                                          11







                                          This works, even when the delimiter is not present in the string.



                                          String.prototype.beforeLastIndex = function (delimiter) {
                                          return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
                                          }

                                          "image".beforeLastIndex(".") // "image"
                                          "image.jpeg".beforeLastIndex(".") // "image"
                                          "image.second.jpeg".beforeLastIndex(".") // "image.second"
                                          "image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"


                                          Can also be used as a one-liner like this:



                                          var filename = "this.is.a.filename.txt";
                                          console.log(filename.split(".").slice(0,-1).join(".") || filename + "");


                                          EDIT: This is a more efficient solution:



                                          String.prototype.beforeLastIndex = function (delimiter) {
                                          return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
                                          }





                                          share|improve this answer















                                          This works, even when the delimiter is not present in the string.



                                          String.prototype.beforeLastIndex = function (delimiter) {
                                          return this.split(delimiter).slice(0,-1).join(delimiter) || this + ""
                                          }

                                          "image".beforeLastIndex(".") // "image"
                                          "image.jpeg".beforeLastIndex(".") // "image"
                                          "image.second.jpeg".beforeLastIndex(".") // "image.second"
                                          "image.second.third.jpeg".beforeLastIndex(".") // "image.second.third"


                                          Can also be used as a one-liner like this:



                                          var filename = "this.is.a.filename.txt";
                                          console.log(filename.split(".").slice(0,-1).join(".") || filename + "");


                                          EDIT: This is a more efficient solution:



                                          String.prototype.beforeLastIndex = function (delimiter) {
                                          return this.substr(0,this.lastIndexOf(delimiter)) || this + ""
                                          }






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Sep 29 '14 at 7:13

























                                          answered Sep 17 '14 at 12:15









                                          Andrew PlankAndrew Plank

                                          628614




                                          628614























                                              8














                                              I like this one because it is a one liner which isn't too hard to read:



                                              filename.substring(0, filename.lastIndexOf('.')) || filename





                                              share|improve this answer




























                                                8














                                                I like this one because it is a one liner which isn't too hard to read:



                                                filename.substring(0, filename.lastIndexOf('.')) || filename





                                                share|improve this answer


























                                                  8












                                                  8








                                                  8







                                                  I like this one because it is a one liner which isn't too hard to read:



                                                  filename.substring(0, filename.lastIndexOf('.')) || filename





                                                  share|improve this answer













                                                  I like this one because it is a one liner which isn't too hard to read:



                                                  filename.substring(0, filename.lastIndexOf('.')) || filename






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Dec 23 '17 at 23:09









                                                  JakubJakub

                                                  1,0441227




                                                  1,0441227























                                                      7














                                                      Another one-liner:



                                                      x.split(".").slice(0, -1).join(".")





                                                      share|improve this answer




























                                                        7














                                                        Another one-liner:



                                                        x.split(".").slice(0, -1).join(".")





                                                        share|improve this answer


























                                                          7












                                                          7








                                                          7







                                                          Another one-liner:



                                                          x.split(".").slice(0, -1).join(".")





                                                          share|improve this answer













                                                          Another one-liner:



                                                          x.split(".").slice(0, -1).join(".")






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Jan 8 '14 at 12:10









                                                          Jacob BundgaardJacob Bundgaard

                                                          655823




                                                          655823























                                                              6














                                                              Here's another regex-based solution:



                                                              filename.replace(/.[^.$]+$/, '');


                                                              This should only chop off the last segment.






                                                              share|improve this answer




























                                                                6














                                                                Here's another regex-based solution:



                                                                filename.replace(/.[^.$]+$/, '');


                                                                This should only chop off the last segment.






                                                                share|improve this answer


























                                                                  6












                                                                  6








                                                                  6







                                                                  Here's another regex-based solution:



                                                                  filename.replace(/.[^.$]+$/, '');


                                                                  This should only chop off the last segment.






                                                                  share|improve this answer













                                                                  Here's another regex-based solution:



                                                                  filename.replace(/.[^.$]+$/, '');


                                                                  This should only chop off the last segment.







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Jan 29 '15 at 22:25









                                                                  Chad JohnsonChad Johnson

                                                                  9,8252687164




                                                                  9,8252687164























                                                                      6














                                                                      I don't know if it's a valid option but I use this:



                                                                      name = filename.split(".");
                                                                      // trimming with pop()
                                                                      name.pop();
                                                                      // getting the name with join()
                                                                      name.join(''); // empty string since default separator is ', '


                                                                      It's not just one operation I know, but at least it should always work!






                                                                      share|improve this answer


























                                                                      • very elegant and working!

                                                                        – danfromisrael
                                                                        Jun 26 '16 at 16:21






                                                                      • 1





                                                                        It should not be name.join('') but name.join('.'). You split by dot but join by comma, so hello.name.txt returns hello, name

                                                                        – Evil
                                                                        Nov 1 '17 at 9:20
















                                                                      6














                                                                      I don't know if it's a valid option but I use this:



                                                                      name = filename.split(".");
                                                                      // trimming with pop()
                                                                      name.pop();
                                                                      // getting the name with join()
                                                                      name.join(''); // empty string since default separator is ', '


                                                                      It's not just one operation I know, but at least it should always work!






                                                                      share|improve this answer


























                                                                      • very elegant and working!

                                                                        – danfromisrael
                                                                        Jun 26 '16 at 16:21






                                                                      • 1





                                                                        It should not be name.join('') but name.join('.'). You split by dot but join by comma, so hello.name.txt returns hello, name

                                                                        – Evil
                                                                        Nov 1 '17 at 9:20














                                                                      6












                                                                      6








                                                                      6







                                                                      I don't know if it's a valid option but I use this:



                                                                      name = filename.split(".");
                                                                      // trimming with pop()
                                                                      name.pop();
                                                                      // getting the name with join()
                                                                      name.join(''); // empty string since default separator is ', '


                                                                      It's not just one operation I know, but at least it should always work!






                                                                      share|improve this answer















                                                                      I don't know if it's a valid option but I use this:



                                                                      name = filename.split(".");
                                                                      // trimming with pop()
                                                                      name.pop();
                                                                      // getting the name with join()
                                                                      name.join(''); // empty string since default separator is ', '


                                                                      It's not just one operation I know, but at least it should always work!







                                                                      share|improve this answer














                                                                      share|improve this answer



                                                                      share|improve this answer








                                                                      edited Feb 29 '16 at 19:16









                                                                      nktssh

                                                                      1,6241321




                                                                      1,6241321










                                                                      answered Nov 29 '15 at 20:44









                                                                      Giacomo CerquoneGiacomo Cerquone

                                                                      1,08321624




                                                                      1,08321624













                                                                      • very elegant and working!

                                                                        – danfromisrael
                                                                        Jun 26 '16 at 16:21






                                                                      • 1





                                                                        It should not be name.join('') but name.join('.'). You split by dot but join by comma, so hello.name.txt returns hello, name

                                                                        – Evil
                                                                        Nov 1 '17 at 9:20



















                                                                      • very elegant and working!

                                                                        – danfromisrael
                                                                        Jun 26 '16 at 16:21






                                                                      • 1





                                                                        It should not be name.join('') but name.join('.'). You split by dot but join by comma, so hello.name.txt returns hello, name

                                                                        – Evil
                                                                        Nov 1 '17 at 9:20

















                                                                      very elegant and working!

                                                                      – danfromisrael
                                                                      Jun 26 '16 at 16:21





                                                                      very elegant and working!

                                                                      – danfromisrael
                                                                      Jun 26 '16 at 16:21




                                                                      1




                                                                      1





                                                                      It should not be name.join('') but name.join('.'). You split by dot but join by comma, so hello.name.txt returns hello, name

                                                                      – Evil
                                                                      Nov 1 '17 at 9:20





                                                                      It should not be name.join('') but name.join('.'). You split by dot but join by comma, so hello.name.txt returns hello, name

                                                                      – Evil
                                                                      Nov 1 '17 at 9:20











                                                                      5














                                                                      Simple one:



                                                                      var n = str.lastIndexOf(".");
                                                                      return n > -1 ? str.substr(0, n) : str;





                                                                      share|improve this answer




























                                                                        5














                                                                        Simple one:



                                                                        var n = str.lastIndexOf(".");
                                                                        return n > -1 ? str.substr(0, n) : str;





                                                                        share|improve this answer


























                                                                          5












                                                                          5








                                                                          5







                                                                          Simple one:



                                                                          var n = str.lastIndexOf(".");
                                                                          return n > -1 ? str.substr(0, n) : str;





                                                                          share|improve this answer













                                                                          Simple one:



                                                                          var n = str.lastIndexOf(".");
                                                                          return n > -1 ? str.substr(0, n) : str;






                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered Jun 21 '16 at 7:59









                                                                          DughDugh

                                                                          13113




                                                                          13113























                                                                              4














                                                                              The accepted answer strips the last extension part only (.jpeg), which might be a good choice in most cases.



                                                                              I once had to strip all extensions (.tar.gz) and the file names were restricted to not contain dots (so 2015-01-01.backup.tar would not be a problem):



                                                                              var name = "2015-01-01_backup.tar.gz";
                                                                              name.replace(/(.[^/.]+)+$/, "");





                                                                              share|improve this answer




























                                                                                4














                                                                                The accepted answer strips the last extension part only (.jpeg), which might be a good choice in most cases.



                                                                                I once had to strip all extensions (.tar.gz) and the file names were restricted to not contain dots (so 2015-01-01.backup.tar would not be a problem):



                                                                                var name = "2015-01-01_backup.tar.gz";
                                                                                name.replace(/(.[^/.]+)+$/, "");





                                                                                share|improve this answer


























                                                                                  4












                                                                                  4








                                                                                  4







                                                                                  The accepted answer strips the last extension part only (.jpeg), which might be a good choice in most cases.



                                                                                  I once had to strip all extensions (.tar.gz) and the file names were restricted to not contain dots (so 2015-01-01.backup.tar would not be a problem):



                                                                                  var name = "2015-01-01_backup.tar.gz";
                                                                                  name.replace(/(.[^/.]+)+$/, "");





                                                                                  share|improve this answer













                                                                                  The accepted answer strips the last extension part only (.jpeg), which might be a good choice in most cases.



                                                                                  I once had to strip all extensions (.tar.gz) and the file names were restricted to not contain dots (so 2015-01-01.backup.tar would not be a problem):



                                                                                  var name = "2015-01-01_backup.tar.gz";
                                                                                  name.replace(/(.[^/.]+)+$/, "");






                                                                                  share|improve this answer












                                                                                  share|improve this answer



                                                                                  share|improve this answer










                                                                                  answered Feb 14 '15 at 20:06









                                                                                  basic6basic6

                                                                                  2,2352644




                                                                                  2,2352644























                                                                                      3














                                                                                      If you have to process a variable that contains the complete path (ex.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") and you want to return just "filename" you can use:



                                                                                      theName = thePath.split("/").slice(-1).join().split(".").shift();


                                                                                      the result will be theName == "filename";



                                                                                      To try it write the following command into the console window of your chrome debugger:
                                                                                      window.location.pathname.split("/").slice(-1).join().split(".").shift()



                                                                                      If you have to process just the file name and its extension (ex.: theNameWithExt = "filename.jpg"):



                                                                                      theName = theNameWithExt.split(".").shift();


                                                                                      the result will be theName == "filename", the same as above;



                                                                                      Notes:




                                                                                      1. The first one is a little bit slower cause performes more
                                                                                        operations; but works in both cases, in other words it can extract
                                                                                        the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.

                                                                                      2. Both solutions work for both local and server files;


                                                                                      But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.



                                                                                      working snippet 1: the complete path




                                                                                      var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
                                                                                      theName = thePath.split("/").slice(-1).join().split(".").shift();
                                                                                      alert(theName);

                                                                                        





                                                                                      working snippet 2: the file name with extension




                                                                                      var theNameWithExt = "filename.jpg";
                                                                                      theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                      alert(theName);

                                                                                        





                                                                                      working snippet 2: the file name with double extension




                                                                                      var theNameWithExt = "filename.tar.gz";
                                                                                      theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                      alert(theName);

                                                                                        








                                                                                      share|improve this answer






























                                                                                        3














                                                                                        If you have to process a variable that contains the complete path (ex.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") and you want to return just "filename" you can use:



                                                                                        theName = thePath.split("/").slice(-1).join().split(".").shift();


                                                                                        the result will be theName == "filename";



                                                                                        To try it write the following command into the console window of your chrome debugger:
                                                                                        window.location.pathname.split("/").slice(-1).join().split(".").shift()



                                                                                        If you have to process just the file name and its extension (ex.: theNameWithExt = "filename.jpg"):



                                                                                        theName = theNameWithExt.split(".").shift();


                                                                                        the result will be theName == "filename", the same as above;



                                                                                        Notes:




                                                                                        1. The first one is a little bit slower cause performes more
                                                                                          operations; but works in both cases, in other words it can extract
                                                                                          the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.

                                                                                        2. Both solutions work for both local and server files;


                                                                                        But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.



                                                                                        working snippet 1: the complete path




                                                                                        var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
                                                                                        theName = thePath.split("/").slice(-1).join().split(".").shift();
                                                                                        alert(theName);

                                                                                          





                                                                                        working snippet 2: the file name with extension




                                                                                        var theNameWithExt = "filename.jpg";
                                                                                        theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                        alert(theName);

                                                                                          





                                                                                        working snippet 2: the file name with double extension




                                                                                        var theNameWithExt = "filename.tar.gz";
                                                                                        theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                        alert(theName);

                                                                                          








                                                                                        share|improve this answer




























                                                                                          3












                                                                                          3








                                                                                          3







                                                                                          If you have to process a variable that contains the complete path (ex.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") and you want to return just "filename" you can use:



                                                                                          theName = thePath.split("/").slice(-1).join().split(".").shift();


                                                                                          the result will be theName == "filename";



                                                                                          To try it write the following command into the console window of your chrome debugger:
                                                                                          window.location.pathname.split("/").slice(-1).join().split(".").shift()



                                                                                          If you have to process just the file name and its extension (ex.: theNameWithExt = "filename.jpg"):



                                                                                          theName = theNameWithExt.split(".").shift();


                                                                                          the result will be theName == "filename", the same as above;



                                                                                          Notes:




                                                                                          1. The first one is a little bit slower cause performes more
                                                                                            operations; but works in both cases, in other words it can extract
                                                                                            the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.

                                                                                          2. Both solutions work for both local and server files;


                                                                                          But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.



                                                                                          working snippet 1: the complete path




                                                                                          var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
                                                                                          theName = thePath.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          working snippet 2: the file name with extension




                                                                                          var theNameWithExt = "filename.jpg";
                                                                                          theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          working snippet 2: the file name with double extension




                                                                                          var theNameWithExt = "filename.tar.gz";
                                                                                          theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            








                                                                                          share|improve this answer















                                                                                          If you have to process a variable that contains the complete path (ex.: thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg") and you want to return just "filename" you can use:



                                                                                          theName = thePath.split("/").slice(-1).join().split(".").shift();


                                                                                          the result will be theName == "filename";



                                                                                          To try it write the following command into the console window of your chrome debugger:
                                                                                          window.location.pathname.split("/").slice(-1).join().split(".").shift()



                                                                                          If you have to process just the file name and its extension (ex.: theNameWithExt = "filename.jpg"):



                                                                                          theName = theNameWithExt.split(".").shift();


                                                                                          the result will be theName == "filename", the same as above;



                                                                                          Notes:




                                                                                          1. The first one is a little bit slower cause performes more
                                                                                            operations; but works in both cases, in other words it can extract
                                                                                            the file name without extension from a given string that contains a path or a file name with ex. While the second works only if the given variable contains a filename with ext like filename.ext but is a little bit quicker.

                                                                                          2. Both solutions work for both local and server files;


                                                                                          But I can't say nothing about neither performances comparison with other answers nor for browser or OS compatibility.



                                                                                          working snippet 1: the complete path




                                                                                          var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
                                                                                          theName = thePath.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          working snippet 2: the file name with extension




                                                                                          var theNameWithExt = "filename.jpg";
                                                                                          theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          working snippet 2: the file name with double extension




                                                                                          var theNameWithExt = "filename.tar.gz";
                                                                                          theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            








                                                                                          var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
                                                                                          theName = thePath.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          var thePath = "http://stackoverflow.com/directory/subdirectory/filename.jpg";
                                                                                          theName = thePath.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          var theNameWithExt = "filename.jpg";
                                                                                          theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          var theNameWithExt = "filename.jpg";
                                                                                          theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          var theNameWithExt = "filename.tar.gz";
                                                                                          theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            





                                                                                          var theNameWithExt = "filename.tar.gz";
                                                                                          theName = theNameWithExt.split("/").slice(-1).join().split(".").shift();
                                                                                          alert(theName);

                                                                                            






                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited Oct 12 '16 at 15:24

























                                                                                          answered Oct 12 '16 at 15:04









                                                                                          willy wonkawilly wonka

                                                                                          327316




                                                                                          327316























                                                                                              3














                                                                                              This can also be done easily with path using the basename and extname methods.



                                                                                              const path = require('path')

                                                                                              path.basename('test.txt', path.extname('test.txt'))





                                                                                              share|improve this answer






























                                                                                                3














                                                                                                This can also be done easily with path using the basename and extname methods.



                                                                                                const path = require('path')

                                                                                                path.basename('test.txt', path.extname('test.txt'))





                                                                                                share|improve this answer




























                                                                                                  3












                                                                                                  3








                                                                                                  3







                                                                                                  This can also be done easily with path using the basename and extname methods.



                                                                                                  const path = require('path')

                                                                                                  path.basename('test.txt', path.extname('test.txt'))





                                                                                                  share|improve this answer















                                                                                                  This can also be done easily with path using the basename and extname methods.



                                                                                                  const path = require('path')

                                                                                                  path.basename('test.txt', path.extname('test.txt'))






                                                                                                  share|improve this answer














                                                                                                  share|improve this answer



                                                                                                  share|improve this answer








                                                                                                  edited Nov 25 '18 at 19:52

























                                                                                                  answered Nov 6 '18 at 2:23









                                                                                                  DBrownDBrown

                                                                                                  1,099915




                                                                                                  1,099915























                                                                                                      2














                                                                                                      var fileName = "something.extension";
                                                                                                      fileName.slice(0, -path.extname(fileName).length) // === "something"





                                                                                                      share|improve this answer




























                                                                                                        2














                                                                                                        var fileName = "something.extension";
                                                                                                        fileName.slice(0, -path.extname(fileName).length) // === "something"





                                                                                                        share|improve this answer


























                                                                                                          2












                                                                                                          2








                                                                                                          2







                                                                                                          var fileName = "something.extension";
                                                                                                          fileName.slice(0, -path.extname(fileName).length) // === "something"





                                                                                                          share|improve this answer













                                                                                                          var fileName = "something.extension";
                                                                                                          fileName.slice(0, -path.extname(fileName).length) // === "something"






                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered Mar 19 '16 at 7:40









                                                                                                          YasYas

                                                                                                          1,5501512




                                                                                                          1,5501512























                                                                                                              2














                                                                                                              Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-



                                                                                                              path.replace(path.substr(path.lastIndexOf('.')), '')






                                                                                                              share|improve this answer




























                                                                                                                2














                                                                                                                Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-



                                                                                                                path.replace(path.substr(path.lastIndexOf('.')), '')






                                                                                                                share|improve this answer


























                                                                                                                  2












                                                                                                                  2








                                                                                                                  2







                                                                                                                  Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-



                                                                                                                  path.replace(path.substr(path.lastIndexOf('.')), '')






                                                                                                                  share|improve this answer













                                                                                                                  Though it's pretty late, I will add another approach to get the filename without extension using plain old JS-



                                                                                                                  path.replace(path.substr(path.lastIndexOf('.')), '')







                                                                                                                  share|improve this answer












                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer










                                                                                                                  answered Apr 5 '18 at 16:50









                                                                                                                  Munim DiboshMunim Dibosh

                                                                                                                  1,77511325




                                                                                                                  1,77511325























                                                                                                                      0














                                                                                                                      This is where regular expressions come in handy! Javascript's .replace() method will take a regular expression, and you can utilize that to accomplish what you want:



                                                                                                                      // assuming var x = filename.jpg or some extension
                                                                                                                      x = x.replace(/(.*).[^.]+$/, "$1");





                                                                                                                      share|improve this answer



















                                                                                                                      • 2





                                                                                                                        Regex is too heavy and unreadable for such simple task

                                                                                                                        – Tomas
                                                                                                                        Jun 4 '14 at 11:13
















                                                                                                                      0














                                                                                                                      This is where regular expressions come in handy! Javascript's .replace() method will take a regular expression, and you can utilize that to accomplish what you want:



                                                                                                                      // assuming var x = filename.jpg or some extension
                                                                                                                      x = x.replace(/(.*).[^.]+$/, "$1");





                                                                                                                      share|improve this answer



















                                                                                                                      • 2





                                                                                                                        Regex is too heavy and unreadable for such simple task

                                                                                                                        – Tomas
                                                                                                                        Jun 4 '14 at 11:13














                                                                                                                      0












                                                                                                                      0








                                                                                                                      0







                                                                                                                      This is where regular expressions come in handy! Javascript's .replace() method will take a regular expression, and you can utilize that to accomplish what you want:



                                                                                                                      // assuming var x = filename.jpg or some extension
                                                                                                                      x = x.replace(/(.*).[^.]+$/, "$1");





                                                                                                                      share|improve this answer













                                                                                                                      This is where regular expressions come in handy! Javascript's .replace() method will take a regular expression, and you can utilize that to accomplish what you want:



                                                                                                                      // assuming var x = filename.jpg or some extension
                                                                                                                      x = x.replace(/(.*).[^.]+$/, "$1");






                                                                                                                      share|improve this answer












                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer










                                                                                                                      answered Nov 22 '10 at 21:32









                                                                                                                      AlexAlex

                                                                                                                      41.4k42137169




                                                                                                                      41.4k42137169








                                                                                                                      • 2





                                                                                                                        Regex is too heavy and unreadable for such simple task

                                                                                                                        – Tomas
                                                                                                                        Jun 4 '14 at 11:13














                                                                                                                      • 2





                                                                                                                        Regex is too heavy and unreadable for such simple task

                                                                                                                        – Tomas
                                                                                                                        Jun 4 '14 at 11:13








                                                                                                                      2




                                                                                                                      2





                                                                                                                      Regex is too heavy and unreadable for such simple task

                                                                                                                      – Tomas
                                                                                                                      Jun 4 '14 at 11:13





                                                                                                                      Regex is too heavy and unreadable for such simple task

                                                                                                                      – Tomas
                                                                                                                      Jun 4 '14 at 11:13











                                                                                                                      0














                                                                                                                      Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';



                                                                                                                          yourStr = yourStr.slice(0, -4); // 'test'





                                                                                                                      share|improve this answer




























                                                                                                                        0














                                                                                                                        Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';



                                                                                                                            yourStr = yourStr.slice(0, -4); // 'test'





                                                                                                                        share|improve this answer


























                                                                                                                          0












                                                                                                                          0








                                                                                                                          0







                                                                                                                          Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';



                                                                                                                              yourStr = yourStr.slice(0, -4); // 'test'





                                                                                                                          share|improve this answer













                                                                                                                          Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';



                                                                                                                              yourStr = yourStr.slice(0, -4); // 'test'






                                                                                                                          share|improve this answer












                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer










                                                                                                                          answered Aug 16 '14 at 2:47









                                                                                                                          SorinNSorinN

                                                                                                                          16923




                                                                                                                          16923























                                                                                                                              0














                                                                                                                              You can use path to maneuver.



                                                                                                                              var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
                                                                                                                              var MYEXT = '.js';
                                                                                                                              var fileName = path.basename(MYPATH, MYEXT);
                                                                                                                              var filePath = path.dirname(MYPATH) + '/' + fileName;


                                                                                                                              Output



                                                                                                                              > filePath
                                                                                                                              '/User/HELLO/WORLD/FILENAME'
                                                                                                                              > fileName
                                                                                                                              'FILENAME'
                                                                                                                              > MYPATH
                                                                                                                              '/User/HELLO/WORLD/FILENAME.js'





                                                                                                                              share|improve this answer




























                                                                                                                                0














                                                                                                                                You can use path to maneuver.



                                                                                                                                var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
                                                                                                                                var MYEXT = '.js';
                                                                                                                                var fileName = path.basename(MYPATH, MYEXT);
                                                                                                                                var filePath = path.dirname(MYPATH) + '/' + fileName;


                                                                                                                                Output



                                                                                                                                > filePath
                                                                                                                                '/User/HELLO/WORLD/FILENAME'
                                                                                                                                > fileName
                                                                                                                                'FILENAME'
                                                                                                                                > MYPATH
                                                                                                                                '/User/HELLO/WORLD/FILENAME.js'





                                                                                                                                share|improve this answer


























                                                                                                                                  0












                                                                                                                                  0








                                                                                                                                  0







                                                                                                                                  You can use path to maneuver.



                                                                                                                                  var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
                                                                                                                                  var MYEXT = '.js';
                                                                                                                                  var fileName = path.basename(MYPATH, MYEXT);
                                                                                                                                  var filePath = path.dirname(MYPATH) + '/' + fileName;


                                                                                                                                  Output



                                                                                                                                  > filePath
                                                                                                                                  '/User/HELLO/WORLD/FILENAME'
                                                                                                                                  > fileName
                                                                                                                                  'FILENAME'
                                                                                                                                  > MYPATH
                                                                                                                                  '/User/HELLO/WORLD/FILENAME.js'





                                                                                                                                  share|improve this answer













                                                                                                                                  You can use path to maneuver.



                                                                                                                                  var MYPATH = '/User/HELLO/WORLD/FILENAME.js';
                                                                                                                                  var MYEXT = '.js';
                                                                                                                                  var fileName = path.basename(MYPATH, MYEXT);
                                                                                                                                  var filePath = path.dirname(MYPATH) + '/' + fileName;


                                                                                                                                  Output



                                                                                                                                  > filePath
                                                                                                                                  '/User/HELLO/WORLD/FILENAME'
                                                                                                                                  > fileName
                                                                                                                                  'FILENAME'
                                                                                                                                  > MYPATH
                                                                                                                                  '/User/HELLO/WORLD/FILENAME.js'






                                                                                                                                  share|improve this answer












                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer










                                                                                                                                  answered Apr 30 '16 at 0:28









                                                                                                                                  Alan DongAlan Dong

                                                                                                                                  2,2931928




                                                                                                                                  2,2931928























                                                                                                                                      0














                                                                                                                                      x.slice(0, -(x.split('.').pop().length + 1));





                                                                                                                                      share|improve this answer




























                                                                                                                                        0














                                                                                                                                        x.slice(0, -(x.split('.').pop().length + 1));





                                                                                                                                        share|improve this answer


























                                                                                                                                          0












                                                                                                                                          0








                                                                                                                                          0







                                                                                                                                          x.slice(0, -(x.split('.').pop().length + 1));





                                                                                                                                          share|improve this answer













                                                                                                                                          x.slice(0, -(x.split('.').pop().length + 1));






                                                                                                                                          share|improve this answer












                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer










                                                                                                                                          answered Nov 25 '17 at 13:08









                                                                                                                                          ishandutta2007ishandutta2007

                                                                                                                                          4,61354157




                                                                                                                                          4,61354157























                                                                                                                                              0














                                                                                                                                              This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.



                                                                                                                                              It works for:




                                                                                                                                              • files without an extension: "myletter"

                                                                                                                                              • files with '.' in the name: "my.letter.txt"

                                                                                                                                              • unknown length of file extension: "my.letter.html"


                                                                                                                                              Here's the code:



                                                                                                                                              var filename = "my.letter.txt" // some filename

                                                                                                                                              var substrings = filename.split('.'); // split the string at '.'
                                                                                                                                              if (substrings.length == 1)
                                                                                                                                              {
                                                                                                                                              return filename; // there was no file extension, file was something like 'myfile'
                                                                                                                                              }
                                                                                                                                              else
                                                                                                                                              {
                                                                                                                                              var ext = substrings.pop(); // remove the last element
                                                                                                                                              var name = substrings.join(""); // rejoin the remaining elements without separator
                                                                                                                                              name = ([name, ext]).join("."); // readd the extension
                                                                                                                                              return name;
                                                                                                                                              }





                                                                                                                                              share|improve this answer


























                                                                                                                                              • fails with hello.tar.gz, output is hellotar.

                                                                                                                                                – Asif Ali
                                                                                                                                                Nov 27 '17 at 6:51











                                                                                                                                              • #AsifAli thanks you are right, I forgot to readd the file extension. I've updated the answer, I hope it works now.

                                                                                                                                                – Little Brain
                                                                                                                                                Nov 27 '17 at 13:15
















                                                                                                                                              0














                                                                                                                                              This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.



                                                                                                                                              It works for:




                                                                                                                                              • files without an extension: "myletter"

                                                                                                                                              • files with '.' in the name: "my.letter.txt"

                                                                                                                                              • unknown length of file extension: "my.letter.html"


                                                                                                                                              Here's the code:



                                                                                                                                              var filename = "my.letter.txt" // some filename

                                                                                                                                              var substrings = filename.split('.'); // split the string at '.'
                                                                                                                                              if (substrings.length == 1)
                                                                                                                                              {
                                                                                                                                              return filename; // there was no file extension, file was something like 'myfile'
                                                                                                                                              }
                                                                                                                                              else
                                                                                                                                              {
                                                                                                                                              var ext = substrings.pop(); // remove the last element
                                                                                                                                              var name = substrings.join(""); // rejoin the remaining elements without separator
                                                                                                                                              name = ([name, ext]).join("."); // readd the extension
                                                                                                                                              return name;
                                                                                                                                              }





                                                                                                                                              share|improve this answer


























                                                                                                                                              • fails with hello.tar.gz, output is hellotar.

                                                                                                                                                – Asif Ali
                                                                                                                                                Nov 27 '17 at 6:51











                                                                                                                                              • #AsifAli thanks you are right, I forgot to readd the file extension. I've updated the answer, I hope it works now.

                                                                                                                                                – Little Brain
                                                                                                                                                Nov 27 '17 at 13:15














                                                                                                                                              0












                                                                                                                                              0








                                                                                                                                              0







                                                                                                                                              This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.



                                                                                                                                              It works for:




                                                                                                                                              • files without an extension: "myletter"

                                                                                                                                              • files with '.' in the name: "my.letter.txt"

                                                                                                                                              • unknown length of file extension: "my.letter.html"


                                                                                                                                              Here's the code:



                                                                                                                                              var filename = "my.letter.txt" // some filename

                                                                                                                                              var substrings = filename.split('.'); // split the string at '.'
                                                                                                                                              if (substrings.length == 1)
                                                                                                                                              {
                                                                                                                                              return filename; // there was no file extension, file was something like 'myfile'
                                                                                                                                              }
                                                                                                                                              else
                                                                                                                                              {
                                                                                                                                              var ext = substrings.pop(); // remove the last element
                                                                                                                                              var name = substrings.join(""); // rejoin the remaining elements without separator
                                                                                                                                              name = ([name, ext]).join("."); // readd the extension
                                                                                                                                              return name;
                                                                                                                                              }





                                                                                                                                              share|improve this answer















                                                                                                                                              This is the code I use to remove the extension from a filename, without using either regex or indexOf (indexOf is not supported in IE8). It assumes that the extension is any text after the last '.' character.



                                                                                                                                              It works for:




                                                                                                                                              • files without an extension: "myletter"

                                                                                                                                              • files with '.' in the name: "my.letter.txt"

                                                                                                                                              • unknown length of file extension: "my.letter.html"


                                                                                                                                              Here's the code:



                                                                                                                                              var filename = "my.letter.txt" // some filename

                                                                                                                                              var substrings = filename.split('.'); // split the string at '.'
                                                                                                                                              if (substrings.length == 1)
                                                                                                                                              {
                                                                                                                                              return filename; // there was no file extension, file was something like 'myfile'
                                                                                                                                              }
                                                                                                                                              else
                                                                                                                                              {
                                                                                                                                              var ext = substrings.pop(); // remove the last element
                                                                                                                                              var name = substrings.join(""); // rejoin the remaining elements without separator
                                                                                                                                              name = ([name, ext]).join("."); // readd the extension
                                                                                                                                              return name;
                                                                                                                                              }






                                                                                                                                              share|improve this answer














                                                                                                                                              share|improve this answer



                                                                                                                                              share|improve this answer








                                                                                                                                              edited Nov 27 '17 at 13:13

























                                                                                                                                              answered Nov 11 '15 at 11:45









                                                                                                                                              Little BrainLittle Brain

                                                                                                                                              426411




                                                                                                                                              426411













                                                                                                                                              • fails with hello.tar.gz, output is hellotar.

                                                                                                                                                – Asif Ali
                                                                                                                                                Nov 27 '17 at 6:51











                                                                                                                                              • #AsifAli thanks you are right, I forgot to readd the file extension. I've updated the answer, I hope it works now.

                                                                                                                                                – Little Brain
                                                                                                                                                Nov 27 '17 at 13:15



















                                                                                                                                              • fails with hello.tar.gz, output is hellotar.

                                                                                                                                                – Asif Ali
                                                                                                                                                Nov 27 '17 at 6:51











                                                                                                                                              • #AsifAli thanks you are right, I forgot to readd the file extension. I've updated the answer, I hope it works now.

                                                                                                                                                – Little Brain
                                                                                                                                                Nov 27 '17 at 13:15

















                                                                                                                                              fails with hello.tar.gz, output is hellotar.

                                                                                                                                              – Asif Ali
                                                                                                                                              Nov 27 '17 at 6:51





                                                                                                                                              fails with hello.tar.gz, output is hellotar.

                                                                                                                                              – Asif Ali
                                                                                                                                              Nov 27 '17 at 6:51













                                                                                                                                              #AsifAli thanks you are right, I forgot to readd the file extension. I've updated the answer, I hope it works now.

                                                                                                                                              – Little Brain
                                                                                                                                              Nov 27 '17 at 13:15





                                                                                                                                              #AsifAli thanks you are right, I forgot to readd the file extension. I've updated the answer, I hope it works now.

                                                                                                                                              – Little Brain
                                                                                                                                              Nov 27 '17 at 13:15











                                                                                                                                              -1














                                                                                                                                              First you have to get correct the extension of file then you can remove it



                                                                                                                                              try this code



                                                                                                                                              <!DOCTYPE html>
                                                                                                                                              <html>
                                                                                                                                              <body>
                                                                                                                                              <p>Click the button to display the array values after the split.</p>
                                                                                                                                              <button onclick="myFunction()">Try it</button>
                                                                                                                                              <p id="demo"></p>
                                                                                                                                              <script>
                                                                                                                                              function getFileName(str){
                                                                                                                                              var res = str.split('.').pop();
                                                                                                                                              alert('filename: ' + str.replace('.' + res, ''));
                                                                                                                                              alert('extension: ' +res);
                                                                                                                                              }
                                                                                                                                              function myFunction() {
                                                                                                                                              getFileName('abc.jpg');
                                                                                                                                              getFileName('abc.def.jpg');
                                                                                                                                              getFileName('abc.def.ghi.jpg');
                                                                                                                                              getFileName('abc.def.ghi.123.jpg');
                                                                                                                                              getFileName('abc.def.ghi.123.456.jpg');
                                                                                                                                              getFileName('abc.jpg.xyz.jpg'); // test with Sébastien comment lol
                                                                                                                                              }
                                                                                                                                              </script>
                                                                                                                                              </body>
                                                                                                                                              </html>





                                                                                                                                              share|improve this answer


























                                                                                                                                              • Try this: getFileName('abc.jpg.xyz.jpg');

                                                                                                                                                – Sébastien
                                                                                                                                                Dec 13 '18 at 10:32











                                                                                                                                              • file name is: 'abc.jpg.xyz', extension is: '.jpg' so what??

                                                                                                                                                – VnDevil
                                                                                                                                                Dec 15 '18 at 7:36











                                                                                                                                              • No, the file name will be 'abc.xyz' as both '.jpg' will be replaced by ''.

                                                                                                                                                – Sébastien
                                                                                                                                                Dec 15 '18 at 11:47











                                                                                                                                              • so you should not named file by that way

                                                                                                                                                – VnDevil
                                                                                                                                                Jan 17 at 3:04











                                                                                                                                              • No, a function should work for every input, the user shouldn't be restricted in its input, at least in this case. The extension of a file is always the last part, so only the last part should used, once and only once.

                                                                                                                                                – Sébastien
                                                                                                                                                Jan 19 at 11:47
















                                                                                                                                              -1














                                                                                                                                              First you have to get correct the extension of file then you can remove it



                                                                                                                                              try this code



                                                                                                                                              <!DOCTYPE html>
                                                                                                                                              <html>
                                                                                                                                              <body>
                                                                                                                                              <p>Click the button to display the array values after the split.</p>
                                                                                                                                              <button onclick="myFunction()">Try it</button>
                                                                                                                                              <p id="demo"></p>
                                                                                                                                              <script>
                                                                                                                                              function getFileName(str){
                                                                                                                                              var res = str.split('.').pop();
                                                                                                                                              alert('filename: ' + str.replace('.' + res, ''));
                                                                                                                                              alert('extension: ' +res);
                                                                                                                                              }
                                                                                                                                              function myFunction() {
                                                                                                                                              getFileName('abc.jpg');
                                                                                                                                              getFileName('abc.def.jpg');
                                                                                                                                              getFileName('abc.def.ghi.jpg');
                                                                                                                                              getFileName('abc.def.ghi.123.jpg');
                                                                                                                                              getFileName('abc.def.ghi.123.456.jpg');
                                                                                                                                              getFileName('abc.jpg.xyz.jpg'); // test with Sébastien comment lol
                                                                                                                                              }
                                                                                                                                              </script>
                                                                                                                                              </body>
                                                                                                                                              </html>





                                                                                                                                              share|improve this answer


























                                                                                                                                              • Try this: getFileName('abc.jpg.xyz.jpg');

                                                                                                                                                – Sébastien
                                                                                                                                                Dec 13 '18 at 10:32











                                                                                                                                              • file name is: 'abc.jpg.xyz', extension is: '.jpg' so what??

                                                                                                                                                – VnDevil
                                                                                                                                                Dec 15 '18 at 7:36











                                                                                                                                              • No, the file name will be 'abc.xyz' as both '.jpg' will be replaced by ''.

                                                                                                                                                – Sébastien
                                                                                                                                                Dec 15 '18 at 11:47











                                                                                                                                              • so you should not named file by that way

                                                                                                                                                – VnDevil
                                                                                                                                                Jan 17 at 3:04











                                                                                                                                              • No, a function should work for every input, the user shouldn't be restricted in its input, at least in this case. The extension of a file is always the last part, so only the last part should used, once and only once.

                                                                                                                                                – Sébastien
                                                                                                                                                Jan 19 at 11:47














                                                                                                                                              -1












                                                                                                                                              -1








                                                                                                                                              -1







                                                                                                                                              First you have to get correct the extension of file then you can remove it



                                                                                                                                              try this code



                                                                                                                                              <!DOCTYPE html>
                                                                                                                                              <html>
                                                                                                                                              <body>
                                                                                                                                              <p>Click the button to display the array values after the split.</p>
                                                                                                                                              <button onclick="myFunction()">Try it</button>
                                                                                                                                              <p id="demo"></p>
                                                                                                                                              <script>
                                                                                                                                              function getFileName(str){
                                                                                                                                              var res = str.split('.').pop();
                                                                                                                                              alert('filename: ' + str.replace('.' + res, ''));
                                                                                                                                              alert('extension: ' +res);
                                                                                                                                              }
                                                                                                                                              function myFunction() {
                                                                                                                                              getFileName('abc.jpg');
                                                                                                                                              getFileName('abc.def.jpg');
                                                                                                                                              getFileName('abc.def.ghi.jpg');
                                                                                                                                              getFileName('abc.def.ghi.123.jpg');
                                                                                                                                              getFileName('abc.def.ghi.123.456.jpg');
                                                                                                                                              getFileName('abc.jpg.xyz.jpg'); // test with Sébastien comment lol
                                                                                                                                              }
                                                                                                                                              </script>
                                                                                                                                              </body>
                                                                                                                                              </html>





                                                                                                                                              share|improve this answer















                                                                                                                                              First you have to get correct the extension of file then you can remove it



                                                                                                                                              try this code



                                                                                                                                              <!DOCTYPE html>
                                                                                                                                              <html>
                                                                                                                                              <body>
                                                                                                                                              <p>Click the button to display the array values after the split.</p>
                                                                                                                                              <button onclick="myFunction()">Try it</button>
                                                                                                                                              <p id="demo"></p>
                                                                                                                                              <script>
                                                                                                                                              function getFileName(str){
                                                                                                                                              var res = str.split('.').pop();
                                                                                                                                              alert('filename: ' + str.replace('.' + res, ''));
                                                                                                                                              alert('extension: ' +res);
                                                                                                                                              }
                                                                                                                                              function myFunction() {
                                                                                                                                              getFileName('abc.jpg');
                                                                                                                                              getFileName('abc.def.jpg');
                                                                                                                                              getFileName('abc.def.ghi.jpg');
                                                                                                                                              getFileName('abc.def.ghi.123.jpg');
                                                                                                                                              getFileName('abc.def.ghi.123.456.jpg');
                                                                                                                                              getFileName('abc.jpg.xyz.jpg'); // test with Sébastien comment lol
                                                                                                                                              }
                                                                                                                                              </script>
                                                                                                                                              </body>
                                                                                                                                              </html>






                                                                                                                                              share|improve this answer














                                                                                                                                              share|improve this answer



                                                                                                                                              share|improve this answer








                                                                                                                                              edited Dec 15 '18 at 7:38

























                                                                                                                                              answered Nov 23 '18 at 6:37









                                                                                                                                              VnDevilVnDevil

                                                                                                                                              453610




                                                                                                                                              453610













                                                                                                                                              • Try this: getFileName('abc.jpg.xyz.jpg');

                                                                                                                                                – Sébastien
                                                                                                                                                Dec 13 '18 at 10:32











                                                                                                                                              • file name is: 'abc.jpg.xyz', extension is: '.jpg' so what??

                                                                                                                                                – VnDevil
                                                                                                                                                Dec 15 '18 at 7:36











                                                                                                                                              • No, the file name will be 'abc.xyz' as both '.jpg' will be replaced by ''.

                                                                                                                                                – Sébastien
                                                                                                                                                Dec 15 '18 at 11:47











                                                                                                                                              • so you should not named file by that way

                                                                                                                                                – VnDevil
                                                                                                                                                Jan 17 at 3:04











                                                                                                                                              • No, a function should work for every input, the user shouldn't be restricted in its input, at least in this case. The extension of a file is always the last part, so only the last part should used, once and only once.

                                                                                                                                                – Sébastien
                                                                                                                                                Jan 19 at 11:47



















                                                                                                                                              • Try this: getFileName('abc.jpg.xyz.jpg');

                                                                                                                                                – Sébastien
                                                                                                                                                Dec 13 '18 at 10:32











                                                                                                                                              • file name is: 'abc.jpg.xyz', extension is: '.jpg' so what??

                                                                                                                                                – VnDevil
                                                                                                                                                Dec 15 '18 at 7:36











                                                                                                                                              • No, the file name will be 'abc.xyz' as both '.jpg' will be replaced by ''.

                                                                                                                                                – Sébastien
                                                                                                                                                Dec 15 '18 at 11:47











                                                                                                                                              • so you should not named file by that way

                                                                                                                                                – VnDevil
                                                                                                                                                Jan 17 at 3:04











                                                                                                                                              • No, a function should work for every input, the user shouldn't be restricted in its input, at least in this case. The extension of a file is always the last part, so only the last part should used, once and only once.

                                                                                                                                                – Sébastien
                                                                                                                                                Jan 19 at 11:47

















                                                                                                                                              Try this: getFileName('abc.jpg.xyz.jpg');

                                                                                                                                              – Sébastien
                                                                                                                                              Dec 13 '18 at 10:32





                                                                                                                                              Try this: getFileName('abc.jpg.xyz.jpg');

                                                                                                                                              – Sébastien
                                                                                                                                              Dec 13 '18 at 10:32













                                                                                                                                              file name is: 'abc.jpg.xyz', extension is: '.jpg' so what??

                                                                                                                                              – VnDevil
                                                                                                                                              Dec 15 '18 at 7:36





                                                                                                                                              file name is: 'abc.jpg.xyz', extension is: '.jpg' so what??

                                                                                                                                              – VnDevil
                                                                                                                                              Dec 15 '18 at 7:36













                                                                                                                                              No, the file name will be 'abc.xyz' as both '.jpg' will be replaced by ''.

                                                                                                                                              – Sébastien
                                                                                                                                              Dec 15 '18 at 11:47





                                                                                                                                              No, the file name will be 'abc.xyz' as both '.jpg' will be replaced by ''.

                                                                                                                                              – Sébastien
                                                                                                                                              Dec 15 '18 at 11:47













                                                                                                                                              so you should not named file by that way

                                                                                                                                              – VnDevil
                                                                                                                                              Jan 17 at 3:04





                                                                                                                                              so you should not named file by that way

                                                                                                                                              – VnDevil
                                                                                                                                              Jan 17 at 3:04













                                                                                                                                              No, a function should work for every input, the user shouldn't be restricted in its input, at least in this case. The extension of a file is always the last part, so only the last part should used, once and only once.

                                                                                                                                              – Sébastien
                                                                                                                                              Jan 19 at 11:47





                                                                                                                                              No, a function should work for every input, the user shouldn't be restricted in its input, at least in this case. The extension of a file is always the last part, so only the last part should used, once and only once.

                                                                                                                                              – Sébastien
                                                                                                                                              Jan 19 at 11:47











                                                                                                                                              -2














                                                                                                                                              I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.






                                                                                                                                              share|improve this answer



















                                                                                                                                              • 2





                                                                                                                                                "If you're going for performance, don't go for javascript at all" - What else are you suggesting to use in web applications..?

                                                                                                                                                – T J
                                                                                                                                                Feb 11 '16 at 16:15











                                                                                                                                              • He doesn't mention web applications.

                                                                                                                                                – Lucas Moeskops
                                                                                                                                                Mar 22 '17 at 22:01






                                                                                                                                              • 1





                                                                                                                                                This question was asked and answer was posted in 2010, 7 years ago, and JavaScript was pretty much used only in web applications. (Node was just born, it didn't even had a guide or NPM at that time)

                                                                                                                                                – T J
                                                                                                                                                Mar 23 '17 at 9:16













                                                                                                                                              • ;-) Still, if performance matters on tasks like this, you might consider doing this on the backend and process the results on the frontend.

                                                                                                                                                – Lucas Moeskops
                                                                                                                                                Mar 23 '17 at 10:23


















                                                                                                                                              -2














                                                                                                                                              I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.






                                                                                                                                              share|improve this answer



















                                                                                                                                              • 2





                                                                                                                                                "If you're going for performance, don't go for javascript at all" - What else are you suggesting to use in web applications..?

                                                                                                                                                – T J
                                                                                                                                                Feb 11 '16 at 16:15











                                                                                                                                              • He doesn't mention web applications.

                                                                                                                                                – Lucas Moeskops
                                                                                                                                                Mar 22 '17 at 22:01






                                                                                                                                              • 1





                                                                                                                                                This question was asked and answer was posted in 2010, 7 years ago, and JavaScript was pretty much used only in web applications. (Node was just born, it didn't even had a guide or NPM at that time)

                                                                                                                                                – T J
                                                                                                                                                Mar 23 '17 at 9:16













                                                                                                                                              • ;-) Still, if performance matters on tasks like this, you might consider doing this on the backend and process the results on the frontend.

                                                                                                                                                – Lucas Moeskops
                                                                                                                                                Mar 23 '17 at 10:23
















                                                                                                                                              -2












                                                                                                                                              -2








                                                                                                                                              -2







                                                                                                                                              I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.






                                                                                                                                              share|improve this answer













                                                                                                                                              I would use something like x.substring(0, x.lastIndexOf('.')). If you're going for performance, don't go for javascript at all :-p No, one more statement really doesn't matter for 99.99999% of all purposes.







                                                                                                                                              share|improve this answer












                                                                                                                                              share|improve this answer



                                                                                                                                              share|improve this answer










                                                                                                                                              answered Nov 22 '10 at 21:29









                                                                                                                                              Lucas MoeskopsLucas Moeskops

                                                                                                                                              4,54222037




                                                                                                                                              4,54222037








                                                                                                                                              • 2





                                                                                                                                                "If you're going for performance, don't go for javascript at all" - What else are you suggesting to use in web applications..?

                                                                                                                                                – T J
                                                                                                                                                Feb 11 '16 at 16:15











                                                                                                                                              • He doesn't mention web applications.

                                                                                                                                                – Lucas Moeskops
                                                                                                                                                Mar 22 '17 at 22:01






                                                                                                                                              • 1





                                                                                                                                                This question was asked and answer was posted in 2010, 7 years ago, and JavaScript was pretty much used only in web applications. (Node was just born, it didn't even had a guide or NPM at that time)

                                                                                                                                                – T J
                                                                                                                                                Mar 23 '17 at 9:16













                                                                                                                                              • ;-) Still, if performance matters on tasks like this, you might consider doing this on the backend and process the results on the frontend.

                                                                                                                                                – Lucas Moeskops
                                                                                                                                                Mar 23 '17 at 10:23
















                                                                                                                                              • 2





                                                                                                                                                "If you're going for performance, don't go for javascript at all" - What else are you suggesting to use in web applications..?

                                                                                                                                                – T J
                                                                                                                                                Feb 11 '16 at 16:15











                                                                                                                                              • He doesn't mention web applications.

                                                                                                                                                – Lucas Moeskops
                                                                                                                                                Mar 22 '17 at 22:01






                                                                                                                                              • 1





                                                                                                                                                This question was asked and answer was posted in 2010, 7 years ago, and JavaScript was pretty much used only in web applications. (Node was just born, it didn't even had a guide or NPM at that time)

                                                                                                                                                – T J
                                                                                                                                                Mar 23 '17 at 9:16













                                                                                                                                              • ;-) Still, if performance matters on tasks like this, you might consider doing this on the backend and process the results on the frontend.

                                                                                                                                                – Lucas Moeskops
                                                                                                                                                Mar 23 '17 at 10:23










                                                                                                                                              2




                                                                                                                                              2





                                                                                                                                              "If you're going for performance, don't go for javascript at all" - What else are you suggesting to use in web applications..?

                                                                                                                                              – T J
                                                                                                                                              Feb 11 '16 at 16:15





                                                                                                                                              "If you're going for performance, don't go for javascript at all" - What else are you suggesting to use in web applications..?

                                                                                                                                              – T J
                                                                                                                                              Feb 11 '16 at 16:15













                                                                                                                                              He doesn't mention web applications.

                                                                                                                                              – Lucas Moeskops
                                                                                                                                              Mar 22 '17 at 22:01





                                                                                                                                              He doesn't mention web applications.

                                                                                                                                              – Lucas Moeskops
                                                                                                                                              Mar 22 '17 at 22:01




                                                                                                                                              1




                                                                                                                                              1





                                                                                                                                              This question was asked and answer was posted in 2010, 7 years ago, and JavaScript was pretty much used only in web applications. (Node was just born, it didn't even had a guide or NPM at that time)

                                                                                                                                              – T J
                                                                                                                                              Mar 23 '17 at 9:16







                                                                                                                                              This question was asked and answer was posted in 2010, 7 years ago, and JavaScript was pretty much used only in web applications. (Node was just born, it didn't even had a guide or NPM at that time)

                                                                                                                                              – T J
                                                                                                                                              Mar 23 '17 at 9:16















                                                                                                                                              ;-) Still, if performance matters on tasks like this, you might consider doing this on the backend and process the results on the frontend.

                                                                                                                                              – Lucas Moeskops
                                                                                                                                              Mar 23 '17 at 10:23







                                                                                                                                              ;-) Still, if performance matters on tasks like this, you might consider doing this on the backend and process the results on the frontend.

                                                                                                                                              – Lucas Moeskops
                                                                                                                                              Mar 23 '17 at 10:23




















                                                                                                                                              draft saved

                                                                                                                                              draft discarded




















































                                                                                                                                              Thanks for contributing an answer to Stack Overflow!


                                                                                                                                              • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                              But avoid



                                                                                                                                              • Asking for help, clarification, or responding to other answers.

                                                                                                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                              To learn more, see our tips on writing great answers.




                                                                                                                                              draft saved


                                                                                                                                              draft discarded














                                                                                                                                              StackExchange.ready(
                                                                                                                                              function () {
                                                                                                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f4250364%2fhow-to-trim-a-file-extension-from-a-string-in-javascript%23new-answer', 'question_page');
                                                                                                                                              }
                                                                                                                                              );

                                                                                                                                              Post as a guest















                                                                                                                                              Required, but never shown





















































                                                                                                                                              Required, but never shown














                                                                                                                                              Required, but never shown












                                                                                                                                              Required, but never shown







                                                                                                                                              Required, but never shown

































                                                                                                                                              Required, but never shown














                                                                                                                                              Required, but never shown












                                                                                                                                              Required, but never shown







                                                                                                                                              Required, but never shown







                                                                                                                                              Popular posts from this blog

                                                                                                                                              A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                                                                                                                                              Calculate evaluation metrics using cross_val_predict sklearn

                                                                                                                                              Insert data from modal to MySQL (multiple modal on website)