Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex to to replace only if the string filename has .jpg or .png extension

I have a huge filename string list, using the regex to to replace only if the string filename has .jpg or .png extension

Means to say if the filename is

Scene.jpg then expected result is IMG_Scene.jpg.

Scenejpgx.docx then expected result is Scenejpgx.docx itself

I tried with

str.replace(/^/i,"IMG_");

but this replaces every strings.

like image 901
Code Guy Avatar asked Aug 30 '25 17:08

Code Guy


1 Answers

You can use

.replace(/.*\.(?:jpg|png)$/i, 'IMG_$&')

See the regex demo

Details

  • .* - any zero or more chars other than line break chars as many as possible
  • \. - a dot
  • (?:jpg|png) - jpg or png
  • $ - end of string.

The $& is the backreference to the whole match, so IMG_$& basically prepends the match with IMG_.

See JavaScript demo:

const strings = ['Scene.jpg','Scenejpgx.docx'];
const re = /.*\.(?:jpg|png)$/i;
strings.forEach( x =>
  console.log(x, '=>', x.replace(re, 'IMG_$&'))
);
like image 197
Wiktor Stribiżew Avatar answered Sep 02 '25 07:09

Wiktor Stribiżew