regex: strip image sizes from URL

487 views Asked by At

I have this image URL's with the typical image sizes in them and need to strip those out to get the clean image URL

I think I got something: https://www.regex101.com/r/qS5aR8/2

Just wanted to ask if there is anything to improve and learn from?

var test_arr = [
    "http://url.com/0304-parapente-lagoon-Reunion-96x64.jpg", 
    "http://url.com/0304-parapente-lagoon-Reunion-960x640.jpg", 
    "http://url.com/0304-parapente-lagoon-Reunion-1500x1000.jpg", 
    "http://url.com/0304-parapente-lagoon-Reunion-1280x840-960x640.jpg", 
    "http://url.com/0304-parapente-lagoon-Reunion.jpg", 
    "http://url.com/520963918_960x540.jpg"
]
for (i = 0; i < test_arr.length; i++) { 
    console.log( test_arr[i].replace(/(-?_?[0-9]+x[0-9])\w+/g, "") );
}
2

There are 2 answers

4
Avinash Raj On BEST ANSWER

I suggest you to use this,

.replace(/(?:[-_]?[0-9]+x[0-9]+)+/g, "")

DEMO

2
bjfletcher On

I'd make it more robust by looking for between 2 and 4 digits:

[_-]?\d{2,4}x\d{2,4}

\d is 3 letters less than [0-9] too. :)