Contents
How to display the last segment of url in JavaScript?
I have the following script which displays the full url of the anchor tag clicked: how do I only get it to display the “file” part of the url in the alert box? 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:
How to find the last occurrence of a character in a URL?
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: That way, you’ll avoid creating an array containing all your URL segments, as split () does.
How to avoid creating array with all url segments?
That way, you’ll avoid creating an array containing all your URL segments, as split () does. Just another solution with regex. The other answers may work if the path is simple, consisting only of simple path elements. But when it contains query params as well, they break. Better use URL object for this instead to get a more robust solution.
How to do a regex for a URL?
The regex that I came up with is: document.location.pathname gets the pathname from the current URL. lastIndexOf get the index of the last occurrence of the following Regex, in our case is /.. The dot means any character, thus, it will not count if the / is the last character on the URL. substring will cut the string between two indexes.
How to get second segment from url stack?
You could boil that down into two lines, if you like, but this way makes it pretty obvious what you’re up to, even without the comment. Once you have the $currentSegment, you can echo it out or use it in an if/else or switch statement to do whatever you like based on the value of the final segment.
What to do with the second segment of Stack Overflow?
Once you have the $currentSegment, you can echo it out or use it in an if/else or switch statement to do whatever you like based on the value of the final segment. Thanks for contributing an answer to Stack Overflow!