简体   繁体   English

获取子字符串和另一个字符串的第一次出现之间的子字符串

[英]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/ . 我的URL路径名称看起来与此类似: /service-area/i-need-this/but-not-this/ The /service-area/ part never changes, and the rest of the path is dynamic. /service-area/部分永远不会更改,其余路径是动态的。

I need to get the part of the URL saying i-need-this . 我需要获得URL的一部分,即i-need-this

Here was my attempt: location.pathname.match(new RegExp('/service-area/' + "(.*)" + '/')); 这是我的尝试: 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. 目的是使/service-area//之间的所有内容都获得,但实际上是到/的最后一次出现,而不是到第一次出现。 So the output from this is actually i-need-this/but-not-this . 因此,此输出实际上是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 : 您也可以使用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