我有这样的网址
让url =“ https://storage.cloud.google.com/dev-radius-backend/merchant/docs/1568875072010.jpg?organizationId=837717194226”
我需要匹配子字符串“ /merchant/docs/1568875072010.jpg”
我已经找到regEx来查找url的基础,但是由于在这种情况下filname位于两者之间而不是结尾,因此我自己无法编写regEx。
但是我找到了一种方法,它不是很有效
var pathArray = url.split('/');
var a = pathArray[6].split('?')
var fileName = '/' + pathArray[4] + '/' + pathArray[5] + '/' + a[0]
我需要fileName为“ /merchant/docs/1568875072010.jpg”
最佳答案
以下正则表达式匹配该模式:\/[^\/]+\/[^\/]+\/[^\/]+(?=\.)\.[^?]+
例:
var url = 'https://storage.cloud.google.com/dev-radius-backend/merchant/docs/1568875072010.jpg?organizationId=837717194226';
var match = url.match(/\/[^\/]+\/[^\/]+\/[^\/]+(?=\.)\.[^?]+/);
if (match) {
console.log(match[0]); // "/merchant/docs/1568875072010.jpg"
document.getElementById('result').innerText = match[0];
}
<span id="result"></span>
正则表达式的解释:
\/
-与文字/
匹配[^\/]+
-至少匹配一次除/
以外的其他任何内容(?=\.)
-正向的断言,断言字符串中当前位置之后紧跟的是文字点\.
-匹配文字点[^?]+
匹配所有非文字问号的内容