Reputation:
I am trying to replace to do a string replace. I would like to replace everything that is between the last /
and .gif
.
I am playing with this snippet of code but can't get it to work (regex is not my strong point).
jQuery
var str = '/foo/folder1/folder2/123img.gif';
var newFileName = 'newImg';
var replaced = str.replace(/\/\d|a-z+-.gif/, newFileName );
$('p').text(replaced);
Output
/foo/folder1/folder2newImg23img.gif
Desired output
/foo/folder1/folder2/newImg.gif
By using d
and |
and a-z
within my regex pattern, I was hoping it would remove digits and letters - but that doesn't seem to be the case.
Fiddle https://jsfiddle.net/hkhfk531/
Upvotes: 1
Views: 50
Reputation: 785156
You can use:
str = str.replace(/[^\/]+(\.gif)$/i, newFileName + '$1')
//=> "/foo/folder1/folder2/newImg.gif"
[^\/]+
matches 1 or more of any char that is not /
before .gif
which is captured in a capturing group.
Here is a lookahead based solution to avoid capturing group:
str = str.replace(/[^\/]+(?=\.gif$)/i, newFileName)
//=> "/foo/folder1/folder2/newImg.gif"
Upvotes: 1