-4

In my current Javascript code I'm using:

.match(/[^/]+$/)

to get the final element of an url. For example, appltying it to:

/country/set/profile/yellow

would return me yellow. Now, I'm facing a problem, as I will need the element that always comes after /country/. for example, applying this new regex to:

/country/set/profile/yellow

would return me set. I've been trying a lot of things, but without any success. Any idea on how to solve this?

5
  • 2
    So, what have you tried and why didn't it work? Commented Mar 28, 2018 at 11:38
  • Here is a great resource for constructing and understanding Regex expressions => regex101.com Commented Mar 28, 2018 at 11:39
  • You know that you don't always need to use regex? Split at /, find the index of country, and +1. Commented Mar 28, 2018 at 11:41
  • Here is a regex idea. Adjust the pattern as required. Commented Mar 28, 2018 at 11:43
  • 1
    Why is that question downvoted so strongly? He said, he tried different things, but without any success. Should he say: ... I tried .* but it didn't work. that you downvoter guys are happy? Commented Mar 28, 2018 at 11:54

1 Answer 1

2

I wouldn't even use a regex for that. You can split your URL and find the correct segment :

let url = "some/stuff/here/country/set/profile/yellow",
    segments = url.split("/"),
    countryIndex = segments.indexOf("country"),
    word = segments[countryIndex + 1]
    
console.log(word) // "set"

Or in a more condensed form :

let segments = "some/stuff/here/country/set/profile/yellow".split("/")
        
console.log( segments[ segments.indexOf("country") +1 ] ) // "set"

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

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.