使用正则表达式从链接中获取图片名称

2022-07-14,,,,

需求介绍

后端的数据接口返回图片链接列表,前端将图片列表渲染出来,展示的时候,需要显示图片名称。如以下的图片链接,那么怎么比较快速的从链接中获取图片的名称呢?

链接例子:https://xxxxxxxx.com/upload/file/customer/dtest1202/customer/t220326-3/1_salesorderattachment_file_41xv.webp?q-sign-algorithm=xxxx

分析

一般来说,图片的名称都是在链接中最后一个/之后,如果链接有携带参数,那么图片名称就是在链接中最后一个/之后、之前。

那么无论使用什么方法,都必须满足上述条件。

链接中存在参数

链接中有参数存在, 即有存在:这种比较简单,因为存在这种独一无二的标志,那么需要先匹配图片名称,再匹配所在的位置即可:

let url = 'https://xxxxxxxx.com/upload/file/customer/dtest1202/customer/t220326-3/1_salesorderattachment_file_41xv.webp?q-sign-algorithm=xxxx'
// 匹配带有英文、_、.、数字的图片名称
const reg = /[\w.]+(?=\?)/g
// 匹配带有中文、英文、_、.、数字的图片名称
const regwithchinese = /[\w.\u4e00-\u9fa5]+(?=\?)/g
const result = url.match(reg)
// 若不存在符合的条件,result值为null,因此需要进行判断
const imgname = result ? result[0] : '不存在'
console.log('imgname: ', imgname);
// 输出 imgname: 1_salesorderattachment_file_41xv.webp

链接中不存在参数

链接中不存在参数,即没有存在: 这种比较麻烦,没有,那么剩下的判断条件就是图片名称处于最后一个/的之后位置了,这个有三种方法:

方法一

第一种利用/为标识,匹配所有非/的字符串,取最后一个:

const url = 'https://xxxxxxxx.com/upload/file/customer/dtest1202/customer/t220326-3/1_salesorderattachment_file_41xv.webp'
const reg = /[^/]+/g
const imgname = url.match(reg).filter(item => item).pop()
console.log('imgname: ', imgname);
// 输出 imgname: 1_salesorderattachment_file_41xv.webp

方法二

第二种是先通过(?!.*/)找出不是以/结尾的字符串的起始位置,可以理解为最后一个/后面的位置,然后匹配字符串:

const url = 'https://xxxxxxxx.com/upload/file/customer/dtest1202/customer/t220326-3/1_salesorderattachment_file_41xv.webp'
const reg = /(?!.*\/).*/g
const imgname = url.match(reg).filter(item => item).pop()
console.log('imgname: ', imgname);
// 输出 imgname: 1_salesorderattachment_file_41xv.webp

方法三

第三种是在前两种结合,利用/为标识,匹配所有非/的字符串,然后找出位置不是在/前面的字符串:

const url = 'https://xxxxxxxx.com/upload/file/customer/dtest1202/customer/t220326-3/1_salesorderattachment_file_41xv.webp'
const reg = /[^/]+(?!.*\/)/g
const imgname = url.match(reg).filter(item => item).pop()
console.log('imgname: ', imgname);
// 输出 imgname: 1_salesorderattachment_file_41xv.webp

总结

到此这篇关于使用正则表达式从链接中获取图片名称的文章就介绍到这了,更多相关正则表达式链接获取图片名称内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《使用正则表达式从链接中获取图片名称.doc》

下载本文的Word格式文档,以方便收藏与打印。