简体   繁体   中英

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

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

This function will return a specific part of the path, counting from the end.
pathFromEnd(url, 0) returns the last part, pathFromEnd(url, 1) returns the penultimate part, and so on... It understands url syntax: with/without protocol, trailing slash, parameters...

 function pathFromEnd(url, pos) { return url.match(new RegExp("^(?:.*?:\\\\/\\\\/)?[^\\\\/]*(?:\\\\/([^\\\\/?]*))*?(?:\\\\/[^\\\\/?]*){" + pos + "}\\\\/?(?:\\\\?.*)?$"))[1]; } alert(pathFromEnd("http://localhost:8080/school/teacher/reports/chapter-quiz/student", 1)); alert(pathFromEnd("localhost:8080/school/teacher/reports/chapter-quiz/student/", 1)); alert(pathFromEnd("www.example.com/school/teacher/reports/chapter-quiz/student?a=b", 1)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM