问题
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".
回答1:
This will change the string containing the file name;
file = file.substr(0, file.lastIndexOf(".")) + ".htm";
For situations where there may not be an extension:
var pos = file.lastIndexOf(".");
file = file.substr(0, pos < 0 ? file.length : pos) + ".htm";
回答2:
file = file.replace(/\.[^.]+$/, '.html');
回答3:
In Node.js:
path.join(path.dirname(file), path.basename(file, path.extname(file)) + '.html')
This works also if the file doesn't have an extension and one of the parent directories has a dot in the name.
回答4:
This probably won't get many upvotes but I couldn't resist.
This code will deal with the edge case where a file might not have an extension already (in which case it will add it). It uses the "tilde trick"
function changeExt (fileName, newExt) {
var _tmp
return fileName.substr(0, ~(_tmp = fileName.lastIndexOf('.')) ? _tmp : fileName.length) + '.' + newExt
}
回答5:
var file = "first.docx";
file = file.split(".");
file = file[0]+".html";
来源:https://stackoverflow.com/questions/5953239/how-do-i-change-file-extension-with-javascript