Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Get last URL segment
// PENDING TESTING..
// Get pathname
var pathName = window.location.pathname;
getLastSegment = function(pathName) {
// declare local
var lastSegment = -1; //false by default
// Check if we even have a pathname
if (pathName.length > 1) {
// Check if last char is '/' and remove it if so
if (pathName.substr(-1) === '/') {
pathName = pathName.substr(0, pathName.length - 1);
}
// Take the last index of '/' and +1 to skip the '/'
lastSegment = pathName.substr(pathName.lastIndexOf('/') + 1);
} else {
// return error if no path
lastSegment = -1
}
// return result
return lastSegment
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment