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
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');
for files without extension and files includes extension. thanks @paul !
filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "-thumb" + '$2');
Either $1 match a filename with no extension or $2 match an extension.
filename = filename.replace(/^([^.]+)$|(\.[^.]+)$/i, '$1' + "_large" + '$2');
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');
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);
}
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);