I have a filename that can have multiple dots in it and could end with any extension:
tro.lo.lo.lo.lo.lo.png
I need to use a regex to repla
'tro.lo.lo.lo.lo.lo.png'.replace(/([^\.]+).+(\.[^.]+)/, "$1.@x2$2")
To match all characters from the beginning of the string until (and including) the last occurence of a character use:
^.*\.(?=[^.]*$) To match the last occurrence of the "." character
^.*_(?=[^.]*$) To match the last occurrence of the "_" character
working demo http://jsfiddle.net/AbDyh/1/
code
var str = 'tro.lo.lo.lo.lo.lo.zip',
replacement = '@2x.';
str = str.replace(/.([^.]*)$/, replacement + '$1');
$('.test').html(str);
alert(str);
You could simply do like this,
> "tro.lo.lo.lo.lo.lo.zip".replace(/^(.*)\./, "$1@2x");
'tro.lo.lo.lo.lo.lo@2xzip'
Why not simply split the string and add said suffix to the second to last entry:
var arr = 'tro.lo.lo.lo.lo.lo.zip'.split('.');
arr[arr.length-2] += '@2x';
var newString = arr.join('.');
You can use the expression \.([^.]*?)
:
str.replace(/\.([^.]*?)$/, "@2x.$1");
You need to reference the $1
subgroup to copy the portion back into the resulting string.