Last segment of URL in jquery

Solution 1:

You can also use the lastIndexOf() function to locate the last occurrence of the / character in your URL, then the substring() function to return the substring starting from that location:

console.log(this.href.substring(this.href.lastIndexOf('/') + 1));

That way, you'll avoid creating an array containing all your URL segments, as split() does.

Solution 2:

var parts = 'http://mywebsite/folder/file'.split('/');
var lastSegment = parts.pop() || parts.pop();  // handle potential trailing slash

console.log(lastSegment);

Solution 3:

window.location.pathname.split("/").pop()

Solution 4:

Just another solution with regex.

var href = location.href;
console.log(href.match(/([^\/]*)\/*$/)[1]);