How do I change file extension with javascript

In Node.js:

path.join(path.dirname(file), path.basename(file, path.extname(file)) + '.md')

or more readably:

// 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.


I'd use this:

path.format({ ...path.parse('/path/to/file.txt'), base: '', ext: '.md' })

to change "/path/to/file.txt" to "/path/to/file.md".


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