code-8
code-8

Reputation: 58642

How do I grab any segment from URL using Javascript?

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

Upvotes: 2

Views: 3631

Answers (3)

code-8
code-8

Reputation: 58642

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

Upvotes: 2

anoraq
anoraq

Reputation: 515

I'd say something like this?

var segments      = location.pathname.split('/');
secondLastSegment = segments[segments.length - 2];

Upvotes: 4

abs
abs

Reputation: 801

you can use this

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

Upvotes: 0

Related Questions