使用正則表達式從鏈接中獲取圖片名稱
需求介紹
后端的數據接口返回圖片鏈接列表,前端將圖片列表渲染出來,展示的時候,需要顯示圖片名稱。如以下的圖片鏈接,那么怎么比較快速的從鏈接中獲取圖片的名稱呢?
鏈接例子: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總結
到此這篇關于使用正則表達式從鏈接中獲取圖片名稱的文章就介紹到這了,更多相關正則表達式鏈接獲取圖片名稱內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

