Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
ma11hew28 Avatar asked Nov 22 '10 21:11

ma11hew28


People also ask

What is extension file in JavaScript?

JavaScript files have the file extension .js.

How do I remove a filename extension in Python?

To remove the extension from a filename using Python, the easiest way is with the os module path. basename() and path. splitext() functions. You can also use the pathlib module and Path and then access the attribute 'stem' to remove the extension from a filename.

How do you trim a file in Unix?

You should be using the command substitution syntax $(command) when you want to execute a command in script/command. name=$(echo "$filename" | cut -f 1 -d '.

How do you delete a file in node?

To delete a file in Node. js, Node FS unlink(path, callback) can be used for asynchronous file operation and unlinkSync(path) can be used for synchronous file operation. In this Node.


2 Answers

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

x.replace(/\.[^/.]+$/, "") 
like image 98
John Hartsock Avatar answered Sep 28 '22 03:09

John Hartsock


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.

like image 21
Jibesh Patra Avatar answered Sep 28 '22 02:09

Jibesh Patra