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

Viewed 387

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.

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_$&'))
);

Related