2

I have a URL : http://localhost:8080/school/teacher/reports/chapter-quiz/student

Getting the last segment, I just need to do this

var lastSegment = location.pathname.split('/').pop();

But how do I grab the one next to the last one ? chapter-quiz

2
  • Can't you just pop() twice? Commented Jul 18, 2015 at 23:54
  • Maybe this old fiddle of mine can help you Commented Jul 19, 2015 at 4:25

3 Answers 3

4

I'd say something like this?

var segments      = location.pathname.split('/');
secondLastSegment = segments[segments.length - 2];
Sign up to request clarification or add additional context in comments.

Comments

2

Split the segments

var pathArray = window.location.pathname.split( '/' );


Create Variables

  • var segment_1 = pathArray[1];
  • var segment_2 = pathArray[2];
  • var segment_3 = pathArray[3];
  • var segment_4 = pathArray[4];

Use it

console.log(segment_4) --> chapter-quiz

Comments

0

you can use this

var t = window.location.pathname.split("/")
t.pop();
t.pop();
t.pop();

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.