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?

4
  • Your code is helpful to point out what the isuse is with your solution. Can you please post an edit to include it? Commented Nov 26, 2018 at 21:38
  • @PaulBeverage I did explain the issue with my solution. My solution gets everything up to the LAST occurrence of /, I need it to go up to the FIRST occurrence of /. Commented Nov 26, 2018 at 21:39
  • 2
    Regex is overkill for your case. Just split URL by / and get 2nd part. Commented Nov 26, 2018 at 21:40
  • Sorry -- my brain apparently lost it at some point...not sure how I missed that. Commented Nov 26, 2018 at 21:40

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.