正则表达式:从 URL 剥离图像大小

regex: strip image sizes from URL

我有这张图片 URL,里面有典型的图片尺寸,需要将它们去掉以获得 clean 图片 URL

我想我得到了一些东西: https://www.regex101.com/r/qS5aR8/2

就想问问有没有什么可以改进和学习的?

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

我建议你使用这个,

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

DEMO

我会通过查找 2 到 4 位数字来使其更健壮:

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

\d 也比 [0-9] 少 3 个字母。 :)