How do I change file extension with javascript

一个人想着一个人 提交于 2019-12-21 03:28:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!