0

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?

chrispytoes
  • 1,714
  • 1
  • 20
  • 53

2 Answers2

2

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?

Mixolydian
  • 215
  • 1
  • 8
0

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);
slider
  • 12,810
  • 1
  • 26
  • 42