Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change file extension with javascript

Does anyone know an easy way to change a file extension in Javascript?

For example, I have a variable with "first.docx" but I need to change it to "first.html".

like image 508
Joseandro Luiz Avatar asked May 10 '11 16:05

Joseandro Luiz


2 Answers

This will change the string containing the file name;

let file = "first.docx";  file = file.substr(0, file.lastIndexOf(".")) + ".htm"; 

For situations where there may not be an extension:

let pos = file.lastIndexOf("."); file = file.substr(0, pos < 0 ? file.length : pos) + ".htm"; 
like image 50
Alex K. Avatar answered Oct 08 '22 01:10

Alex K.


In Node.js:

// extension should include the dot, for example '.html' function changeExtension(file, extension) {   const basename = path.basename(file, path.extname(file))   return path.join(path.dirname(file), basename + extension) } 

Unlike the accepted answer, this works for edge cases such as if the file doesn't have an extension and one of the parent directories has a dot in their name.

like image 29
emlai Avatar answered Oct 08 '22 02:10

emlai