如何编写函数从URL提取图片扩展名 无扩展名时返回指定值
需求说明
编写功能函数实现以下逻辑:
- 从输入的URL中提取
.png、.svg等格式的图片扩展名 - 若URL中不存在这类图片文件扩展名,返回
"Yes"
测试用例
- 无扩展名URL:输入
https://test.123.com/file/AnoxcdsffcARw,返回"Yes" - 带图片扩展名URL:输入
https://test.123.com/file/AnoxcdsffcARw.png,返回png
代码实现(通用逻辑可跨语言迁移,以下为JavaScript示例)
function getImgExtFromUrl(url) { // 剔除查询参数、锚点干扰 const purePath = url.split(/[?#]/)[0]; const lastPathPart = purePath.split('/').pop(); // 匹配常见图片后缀,不区分大小写 const extMatch = lastPathPart.match(/\.(png|svg|jpg|jpeg|gif|webp|bmp)$/i); return extMatch ? extMatch[1].toLowerCase() : "Yes"; } // 测试运行 // 无扩展名场景 console.log(getImgExtFromUrl("https://test.123.com/file/AnoxcdsffcARw")); // 输出 Yes // 带png扩展名场景 console.log(getImgExtFromUrl("https://test.123.com/file/AnoxcdsffcARw.png")); // 输出 png // 带查询参数、锚点的svg场景 console.log(getImgExtFromUrl("https://test.123.com/file/demo.svg?version=1.0#hash")); // 输出 svg
实现要点:处理URL时要先剥离查询参数、哈希片段,避免路径外的点号造成误判;匹配规则加大小写兼容,覆盖大写后缀的异常场景。
内容的提问来源于stack exchange,提问作者Derek Hough
相关产品推荐
相关产品推荐

