Reputation: 1889
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?
Upvotes: 0
Views: 179
Reputation: 12990
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);
Upvotes: 0
Reputation: 215
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?
Upvotes: 2