How to trim a file extension from a String in JavaScript?
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
add a comment |
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
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
add a comment |
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
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
javascript replace substring substr indexof
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
add a comment |
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
add a comment |
24 Answers
24
active
oldest
votes
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.
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'sx[0..-5]
, andx.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
add a comment |
Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg
or .html
x.replace(/.[^/.]+$/, "")
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
|
show 4 more comments
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.
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
add a comment |
x.length-4
only accounts for extensions of 3 characters. What if you have filename.jpeg
or 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];
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
|
show 5 more comments
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);
}
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
add a comment |
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.
add a comment |
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 + ""
}
add a comment |
I like this one because it is a one liner which isn't too hard to read:
filename.substring(0, filename.lastIndexOf('.')) || filename
add a comment |
Another one-liner:
x.split(".").slice(0, -1).join(".")
add a comment |
Here's another regex-based solution:
filename.replace(/.[^.$]+$/, '');
This should only chop off the last segment.
add a comment |
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!
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, sohello.name.txt
returnshello, name
– Evil
Nov 1 '17 at 9:20
add a comment |
Simple one:
var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
add a comment |
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(/(.[^/.]+)+$/, "");
add a comment |
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:
- 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. - 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);
add a comment |
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'))
add a comment |
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
add a comment |
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('.')), '')
add a comment |
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");
2
Regex is too heavy and unreadable for such simple task
– Tomas
Jun 4 '14 at 11:13
add a comment |
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
yourStr = yourStr.slice(0, -4); // 'test'
add a comment |
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'
add a comment |
x.slice(0, -(x.split('.').pop().length + 1));
add a comment |
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;
}
fails withhello.tar.gz
, output ishellotar
.
– 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
add a comment |
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>
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
add a comment |
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.
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
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'sx[0..-5]
, andx.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
add a comment |
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.
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'sx[0..-5]
, andx.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
add a comment |
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.
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.
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'sx[0..-5]
, andx.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
add a comment |
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'sx[0..-5]
, andx.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
add a comment |
Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg
or .html
x.replace(/.[^/.]+$/, "")
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
|
show 4 more comments
Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg
or .html
x.replace(/.[^/.]+$/, "")
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
|
show 4 more comments
Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg
or .html
x.replace(/.[^/.]+$/, "")
Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg
or .html
x.replace(/.[^/.]+$/, "")
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
|
show 4 more comments
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
|
show 4 more comments
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.
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
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
x.length-4
only accounts for extensions of 3 characters. What if you have filename.jpeg
or 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];
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
|
show 5 more comments
x.length-4
only accounts for extensions of 3 characters. What if you have filename.jpeg
or 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];
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
|
show 5 more comments
x.length-4
only accounts for extensions of 3 characters. What if you have filename.jpeg
or 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];
x.length-4
only accounts for extensions of 3 characters. What if you have filename.jpeg
or 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];
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
|
show 5 more comments
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
|
show 5 more comments
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);
}
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
add a comment |
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);
}
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
add a comment |
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);
}
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);
}
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
add a comment |
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
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Dec 16 '15 at 0:01
blah238blah238
75121139
75121139
add a comment |
add a comment |
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 + ""
}
add a comment |
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 + ""
}
add a comment |
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 + ""
}
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 + ""
}
edited Sep 29 '14 at 7:13
answered Sep 17 '14 at 12:15
Andrew PlankAndrew Plank
628614
628614
add a comment |
add a comment |
I like this one because it is a one liner which isn't too hard to read:
filename.substring(0, filename.lastIndexOf('.')) || filename
add a comment |
I like this one because it is a one liner which isn't too hard to read:
filename.substring(0, filename.lastIndexOf('.')) || filename
add a comment |
I like this one because it is a one liner which isn't too hard to read:
filename.substring(0, filename.lastIndexOf('.')) || filename
I like this one because it is a one liner which isn't too hard to read:
filename.substring(0, filename.lastIndexOf('.')) || filename
answered Dec 23 '17 at 23:09
JakubJakub
1,0441227
1,0441227
add a comment |
add a comment |
Another one-liner:
x.split(".").slice(0, -1).join(".")
add a comment |
Another one-liner:
x.split(".").slice(0, -1).join(".")
add a comment |
Another one-liner:
x.split(".").slice(0, -1).join(".")
Another one-liner:
x.split(".").slice(0, -1).join(".")
answered Jan 8 '14 at 12:10
Jacob BundgaardJacob Bundgaard
655823
655823
add a comment |
add a comment |
Here's another regex-based solution:
filename.replace(/.[^.$]+$/, '');
This should only chop off the last segment.
add a comment |
Here's another regex-based solution:
filename.replace(/.[^.$]+$/, '');
This should only chop off the last segment.
add a comment |
Here's another regex-based solution:
filename.replace(/.[^.$]+$/, '');
This should only chop off the last segment.
Here's another regex-based solution:
filename.replace(/.[^.$]+$/, '');
This should only chop off the last segment.
answered Jan 29 '15 at 22:25
Chad JohnsonChad Johnson
9,8252687164
9,8252687164
add a comment |
add a comment |
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!
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, sohello.name.txt
returnshello, name
– Evil
Nov 1 '17 at 9:20
add a comment |
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!
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, sohello.name.txt
returnshello, name
– Evil
Nov 1 '17 at 9:20
add a comment |
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!
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!
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, sohello.name.txt
returnshello, name
– Evil
Nov 1 '17 at 9:20
add a comment |
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, sohello.name.txt
returnshello, 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
add a comment |
Simple one:
var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
add a comment |
Simple one:
var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
add a comment |
Simple one:
var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
Simple one:
var n = str.lastIndexOf(".");
return n > -1 ? str.substr(0, n) : str;
answered Jun 21 '16 at 7:59
DughDugh
13113
13113
add a comment |
add a comment |
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(/(.[^/.]+)+$/, "");
add a comment |
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(/(.[^/.]+)+$/, "");
add a comment |
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(/(.[^/.]+)+$/, "");
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(/(.[^/.]+)+$/, "");
answered Feb 14 '15 at 20:06
basic6basic6
2,2352644
2,2352644
add a comment |
add a comment |
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:
- 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. - 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);
add a comment |
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:
- 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. - 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);
add a comment |
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:
- 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. - 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);
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:
- 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. - 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);
edited Oct 12 '16 at 15:24
answered Oct 12 '16 at 15:04
willy wonkawilly wonka
327316
327316
add a comment |
add a comment |
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'))
add a comment |
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'))
add a comment |
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'))
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'))
edited Nov 25 '18 at 19:52
answered Nov 6 '18 at 2:23
DBrownDBrown
1,099915
1,099915
add a comment |
add a comment |
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
add a comment |
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
add a comment |
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
answered Mar 19 '16 at 7:40
YasYas
1,5501512
1,5501512
add a comment |
add a comment |
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('.')), '')
add a comment |
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('.')), '')
add a comment |
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('.')), '')
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('.')), '')
answered Apr 5 '18 at 16:50
Munim DiboshMunim Dibosh
1,77511325
1,77511325
add a comment |
add a comment |
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");
2
Regex is too heavy and unreadable for such simple task
– Tomas
Jun 4 '14 at 11:13
add a comment |
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");
2
Regex is too heavy and unreadable for such simple task
– Tomas
Jun 4 '14 at 11:13
add a comment |
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");
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");
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
add a comment |
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
add a comment |
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
yourStr = yourStr.slice(0, -4); // 'test'
add a comment |
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
yourStr = yourStr.slice(0, -4); // 'test'
add a comment |
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
yourStr = yourStr.slice(0, -4); // 'test'
Another one liner - we presume our file is a jpg picture >> ex: var yourStr = 'test.jpg';
yourStr = yourStr.slice(0, -4); // 'test'
answered Aug 16 '14 at 2:47
SorinNSorinN
16923
16923
add a comment |
add a comment |
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'
add a comment |
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'
add a comment |
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'
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'
answered Apr 30 '16 at 0:28
Alan DongAlan Dong
2,2931928
2,2931928
add a comment |
add a comment |
x.slice(0, -(x.split('.').pop().length + 1));
add a comment |
x.slice(0, -(x.split('.').pop().length + 1));
add a comment |
x.slice(0, -(x.split('.').pop().length + 1));
x.slice(0, -(x.split('.').pop().length + 1));
answered Nov 25 '17 at 13:08
ishandutta2007ishandutta2007
4,61354157
4,61354157
add a comment |
add a comment |
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;
}
fails withhello.tar.gz
, output ishellotar
.
– 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
add a comment |
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;
}
fails withhello.tar.gz
, output ishellotar
.
– 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
add a comment |
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;
}
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;
}
edited Nov 27 '17 at 13:13
answered Nov 11 '15 at 11:45
Little BrainLittle Brain
426411
426411
fails withhello.tar.gz
, output ishellotar
.
– 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
add a comment |
fails withhello.tar.gz
, output ishellotar
.
– 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
add a comment |
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>
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
add a comment |
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>
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
add a comment |
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>
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>
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
add a comment |
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
add a comment |
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.
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
add a comment |
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.
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
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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