When working on a project, you may come across the need to extract the last segment from a path or URL. Whether it’s a filesystem path or a website URL, the following JavaScript code can help you achieve that:
const lastItem = thePath.substring(thePath.lastIndexOf('/') + 1);
To understand how this code works, let’s break it down:
- We define a
thePath
string that represents the path or URL, such as/Users/Flavio/Desktop
. - By calling
lastIndexOf('/')
onthePath
, we find the index of the last occurrence of the forward slash (/) character. - The resulting index is then passed as an argument to the
substring()
method, which extracts a portion of the string starting from the position of the last forward slash, plus 1 (to exclude the forward slash itself). - Finally, we assign the extracted segment to the
lastItem
variable.
If you prefer a reusable function, you can create one like this:
const getLastItem = thePath => thePath.substring(thePath.lastIndexOf('/') + 1);
// Usage examples
getLastItem('/Users'); // Returns an empty string
getLastItem('/Users/Flavio'); // Returns "Flavio"
getLastItem('/Users/Flavio/test.jpg'); // Returns "test.jpg"
getLastItem('https://flavicopes.com/test'); // Returns "test"
By using this code, you can easily extract the last segment from a path or URL in your JavaScript applications.