简体   繁体   中英

Get substring between substring and first occurrence of another string

I have URL pathnames that look similar to this: /service-area/i-need-this/but-not-this/ . The /service-area/ part never changes, and the rest of the path is dynamic.

I need to get the part of the URL saying i-need-this .

Here was my attempt: location.pathname.match(new RegExp('/service-area/' + "(.*)" + '/')); .

The goal was to get everything between /service-area/ and / but it's actually going up to the last occurrence of / , not the first occurrance. So the output from this is actually i-need-this/but-not-this .

I'm not so good with regex, is there a way it can be tweaked to get the desired result?

You need a lazy regex rather than a greedy one - so (.*?) instead of (.*) . See also: What do 'lazy' and 'greedy' mean in the context of regular expressions?

You can do this without a regex too using replace and split :

 var path = '/service-area/i-need-this/but-not-this/'; var res = path.replace('/service-area/', '').split('/')[0]; console.log(res); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM