最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How do I grab any segment from URL using Javascript? - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Jul 18, 2015 at 23:02 Patel 1,4781 gold badge13 silver badges24 bronze badges asked Jul 18, 2015 at 22:59 code-8code-8 58.9k120 gold badges391 silver badges670 bronze badges 2
  • Can't you just pop() twice? – Frank Bryce Commented Jul 18, 2015 at 23:54
  • Maybe this old fiddle of mine can help you – Tim Vermaelen Commented Jul 19, 2015 at 4:25
Add a ment  | 

3 Answers 3

Reset to default 4

I'd say something like this?

var segments      = location.pathname.split('/');
secondLastSegment = segments[segments.length - 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

you can use this

var t = window.location.pathname.split("/")
t.pop();
t.pop();
t.pop();
发布评论

评论列表(0)

  1. 暂无评论