Insert a string before the extension in a filename

2020-05-25 01:49发布

问题:

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

回答1:

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');


回答2:

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("."));


回答3:

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);
} 


回答4:

var s = '../Course/Assess/Responsive_Course_1_1.png'
s.replace(/\.png$/, '_large.png');

This will do the job. By the way, it's night here. :)

UPDATE:

A more general way would be this:

var s = '../Course/Assess/Responsive_Course_1_1.png';
s.replace(/(\.[^\.]+)$/, '_large$1');


回答5:

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

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


回答6:

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

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



回答7:

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