How do I change file extension with javascript

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;

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

file = file.replace(/.[^.]+$/, '.html');

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
}
链接地址: http://www.djcxy.com/p/75056.html

上一篇: 使用jQuery过滤多个<ul>列表

下一篇: 如何使用JavaScript更改文件扩展名