日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

使用正則表達式從鏈接中獲取圖片名稱_正則表達式

作者:水開泡茶 ? 更新時間: 2022-07-28 編程語言

需求介紹

后端的數據接口返回圖片鏈接列表,前端將圖片列表渲染出來,展示的時候,需要顯示圖片名稱。如以下的圖片鏈接,那么怎么比較快速的從鏈接中獲取圖片的名稱呢?

鏈接例子: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

總結

原文鏈接:https://juejin.cn/post/7102672603210317860

欄目分類
最近更新