欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2022年05月31日 10:39:57   作者:水開泡茶  
正則表達式有時可用來判斷是否包含某些數(shù)據(jù),有時可用來獲取匹配數(shù)據(jù),下面這篇文章主要給大家介紹了關于使用正則表達式從鏈接中獲取圖片名稱的相關資料,需要的朋友可以參考下

需求介紹

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

鏈接例子:https://xxxxxxxx.com/Upload/File/Customer/Dtest1202/Customer/T220326-3/1_SalesOrderAttachment_File_41XV.webp?q-sign-algorithm=xxxx

分析

一般來說,圖片的名稱都是在鏈接中最后一個/之后,如果鏈接有攜帶參數(shù),那么圖片名稱就是在鏈接中最后一個/之后、?之前。

那么無論使用什么方法,都必須滿足上述條件。

鏈接中存在參數(shù)

鏈接中有參數(shù)存在, 即有存在:這種比較簡單,因為存在這種獨一無二的標志,那么需要先匹配圖片名稱,再匹配所在的位置即可:

let url = 'https://xxxxxxxx.com/Upload/File/Customer/Dtest1202/Customer/T220326-3/1_SalesOrderAttachment_File_41XV.webp?q-sign-algorithm=xxxx'
// 匹配帶有英文、_、.、數(shù)字的圖片名稱
const reg = /[\w.]+(?=\?)/g
// 匹配帶有中文、英文、_、.、數(shù)字的圖片名稱
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

鏈接中不存在參數(shù)

鏈接中不存在參數(shù),即沒有?存在: 這種比較麻煩,沒有?,那么剩下的判斷條件就是圖片名稱處于最后一個/的之后位置了,這個有三種方法:

方法一

第一種利用/為標識,匹配所有非/的字符串,取最后一個:

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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論