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".
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";
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With