Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a string before the extension in a filename

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 
like image 950
Jason Ryan Avatar asked May 29 '12 15:05

Jason Ryan


People also ask

What is the part of filename before extension?

It's called the basename. In fact, there's a unix/linux command for it: basename - strip directory and suffix from filenames.

Does a filename include the extension?

A filename may (depending on the file system) include: name – base name of the file. extension (format or extension) – indicates the content of the file (e.g. . txt , .exe , .


2 Answers

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'); 
like image 76
ziad-saab Avatar answered Oct 20 '22 18:10

ziad-saab


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); }  
like image 40
Maria Avatar answered Oct 20 '22 18:10

Maria