Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match only the last instance of a pattern with Javascript regexp

I want to remove size data from a file name like

var src = 'http://az648995.vo.msecnd.net/win/2015/11/Halo-1024x551.jpg';
src = src.replace(
     /-\d+x\d+(.\S+)$/,
    function( match, contents, offset, s ) {
        return contents;
    }
);

this works as expected and i get

http://az648995.vo.msecnd.net/win/2015/11/Halo.jpg

But if I have a filename like

http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.jpg

it returns

http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-1024x512.jpg

instead of the desired

http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000.jpg
like image 243
Nicola Peluchetti Avatar asked Dec 25 '22 10:12

Nicola Peluchetti


2 Answers

Your regex does not work as expected primarily because of an unescaped dot in (.\S+)$ part. An unescaped . matches any character but a newline. However, \S matches any non-whitespace, including a .. Besides unnecessary backtracking, you may get an unexpected result with a string like http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.MORE_TEXT_HERE.jpg.

Assuming the extension is the part of a string after the last dot, you can use

-\d+x\d+(\.[^.\s]+)$

See regex demo

The nagated character class [^.\s] matches any character but whitespace and a literal . symbol. Note that there is no point in using a callback function inside a replace, you can use a mere $1 backreference.

JS demo:

var src = 'http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.jpg';
src = src.replace(/-\d+x\d+(.[^.\s]+)$/, "$1");
document.body.innerHTML = src;
like image 110
Wiktor Stribiżew Avatar answered Jan 17 '23 15:01

Wiktor Stribiżew


Try escaping the . and you will be fine:

/-\d+x\d+(\.\S+)$/
like image 33
Darin Dimitrov Avatar answered Jan 17 '23 16:01

Darin Dimitrov