For example, assuming that x = filename.jpg
, I want to get filename
, where filename
could be any file name (Let\'s assume the file nam
var fileName = "something.extension";
fileName.slice(0, -path.extname(fileName).length) // === "something"
In node.js, the name of the file without the extension can be obtained as follows.
const path = require('path');
const filename = 'hello.html';
path.parse(filename).name; // hello
path.parse(filename).ext; // .html
Further explanation at Node.js documentation page.
Another one-liner:
x.split(".").slice(0, -1).join(".")
x.slice(0, -(x.split('.').pop().length + 1));
Not sure what would perform faster but this would be more reliable when it comes to extension like .jpeg
or .html
x.replace(/\.[^/.]+$/, "")
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];