Javascript 如何使用javascript更改文件扩展名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5953239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change file extension with javascript
提问by JLuiz
Does anyone know an easy way to change a file extension in Javascript?
有谁知道在 Javascript 中更改文件扩展名的简单方法?
For example, I have a variable with "first.docx" but I need to change it to "first.html".
例如,我有一个带有“first.docx”的变量,但我需要将其更改为“first.html”。
回答by Alex K.
This will change the string containingthe 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";
回答by ChaosPandion
file = file.replace(/\.[^.]+$/, '.html');
回答by emlai
In Node.js:
在 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.
如果文件没有扩展名并且父目录之一的名称中有一个点,这也适用。
回答by Merc
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
}
回答by mizkichan
I'd use this:
我会用这个:
path.format({ ...path.parse('/foo/bar/baz.hoge'), base: undefined, ext: '.fuga' })
回答by Maxime
var file = "first.docx";
file = file.split(".");
file = file[0]+".html";