Match only last instance of template with javascript regexp

I want to delete size data from a file name, e.g.

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;
    }
);

it works as expected and I get

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

But if I have a file name like

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

he 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
+4
source share
4 answers

Your regex does not work as expected, mainly due to the drop-down point in the part (.\S+)$. Unescaped .matches any character, but matches a new line. However, it \Smatches any with no spaces, including .. Besides an unnecessary return, you can get an unexpected result with a string, for example http://az648995.vo.msecnd.net/win/2015/11/slot-Drake-08-2000x1000-1024x512.MORE_TEXT_HERE.jpg.

, ,

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

- regex

nagated character [^.\s] , .. : , $1 .

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;
Hide result
+5

., :

/-\d+x\d+(\.\S+)$/
+3

Change the regex slightly to a little more explicit:

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

Regular expression can be simplified to the next

Replace

-\d+x\d+(\.\S+)

FROM

$1
0
source

Source: https://habr.com/ru/post/1622744/


All Articles