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

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.


Solution 1:

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.

Solution 2:

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

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

Solution 3:

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.

Related:  SystemJS - moment is not a function

Solution 4:

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


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(/\..+$/, '');


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


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];

Solution 5:

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);

Solution 6:

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.

Related:  What does $.when.apply($, someArray) do?