[英]Get substring between substring and first occurrence of another string
我的URL路徑名稱看起來與此類似: /service-area/i-need-this/but-not-this/
。 /service-area/
部分永遠不會更改,其余路徑是動態的。
我需要獲得URL的一部分,即i-need-this
。
這是我的嘗試: location.pathname.match(new RegExp('/service-area/' + "(.*)" + '/'));
。
目的是使/service-area/
和/
之間的所有內容都獲得,但實際上是到/
的最后一次出現,而不是到第一次出現。 因此,此輸出實際上是i-need-this/but-not-this
。
我對正則表達式不太滿意,有沒有一種方法可以對其進行調整以獲得期望的結果?
您需要一個懶惰的正則表達式而不是一個貪婪的正則表達式-所以(.*?)
而不是(.*)
。 另請參閱: 在正則表達式的上下文中,“懶惰”和“貪婪”是什么意思?
您也可以使用replace
和split
而無需使用正則表達式:
var path = '/service-area/i-need-this/but-not-this/'; var res = path.replace('/service-area/', '').split('/')[0]; console.log(res);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.