簡體   English   中英

獲取子字符串和另一個字符串的第一次出現之間的子字符串

[英]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

我對正則表達式不太滿意,有沒有一種方法可以對其進行調整以獲得期望的結果?

您需要一個懶惰的正則表達式而不是一個貪婪的正則表達式-所以(.*?)而不是(.*) 另請參閱: 在正則表達式的上下文中,“懶惰”和“貪婪”是什么意思?

您也可以使用replacesplit而無需使用正則表達式:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM