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

时间:2018-11-26 21:36:05

标签: javascript

我有一个类似于以下内容的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

我对正则表达式不太满意,有没有一种方法可以对其进行调整以获得期望的结果?

2 个答案:

答案 0 :(得分:2)

您需要一个懒惰的正则表达式而不是一个贪婪的正则表达式-因此(.*?)而不是(.*)。另请参阅:What do 'lazy' and 'greedy' mean in the context of regular expressions?

答案 1 :(得分:0)

您也可以使用 (?<! [-+.\da-zA-Z_] ) # Word and symbol boundary [+-]? # Optional +/- (?: \d+ # Starts with a digit (?: \. \d* )? | # or, \. \d+ # Starts with a decimal point ) (?: [eE] [+-]? \d+ )? # Optional exponent \b # Just a word boundary replace,而无需使用正则表达式:

split