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

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


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

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


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"path.parse(filename).base; //=> "hello.html"

Further explanation at Node.js documentation page.


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.