Insert a string before the extension in a filename

2020-05-25 01:29发布

How can I insert a string before the extension in an image filename? For example, I need to convert this:

../Course/Assess/Responsive_Course_1_1.png

to this:

../Course/Assess/Responsive_Course_1_1_large.png

7条回答
beautiful°
2楼-- · 2020-05-25 02:12

If you are not sure what could be the incoming file's extension then this helps:

function renameFileA(imgUrl) {
  var extension = `.${imgUrl.split('.').pop()}`
  var [fileName] = imgUrl.split(extension);
  return `${fileName}_large${extension}`;
};

// this is clean but I don't understand what's going on till I do research ;)
function renameFileB(imgUrl) {
  return imgUrl.replace(/(\.[\w\d_-]+)$/i, '_large$1');
};

var valA = renameFileA('http//www.app.com/img/thumbnails/vid-th.png');
var valB = renameFileB('http//www.app.com/img/thumbnails/vid-th.jpg');

console.log('valA', valA);
console.log('valB', valB);

查看更多
祖国的老花朵
3楼-- · 2020-05-25 02:19

If we assume that an extension is any series of letters, numbers, underscore or dash after the last dot in the file name, then:

filename = filename.replace(/(\.[\w\d_-]+)$/i, '_large$1');
查看更多
We Are One
4楼-- · 2020-05-25 02:20

Use javascript lastIndexOf, something like:

var s = "Courses/Assess/Responsive_Cousre_1_1.png";
var new_string = s.substring(0, s.lastIndexOf(".")) + "_large" + s.substring(s.lastIndexOf("."));
查看更多
淡お忘
5楼-- · 2020-05-25 02:21

None of the answers works if file doesn't have extension. Here's a solution that works for all cases.

function appendToFilename(filename, string){
    var dotIndex = filename.lastIndexOf(".");
    if (dotIndex == -1) return filename + string;
    else return filename.substring(0, dotIndex) + string + filename.substring(dotIndex);
} 
查看更多
太酷不给撩
6楼-- · 2020-05-25 02:23

for files without extension and files includes extension. thanks @paul !

filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "-thumb" + '$2');

查看更多
再贱就再见
7楼-- · 2020-05-25 02:30

Either $1 match a filename with no extension or $2 match an extension.

filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "_large" + '$2');
查看更多
登录 后发表回答