How to extract the last segment from a path or URL using JavaScript
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:
1 | 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:
1 | const getLastItem = thePath => thePath.substring(thePath.lastIndexOf('/') + 1); |
By using this code, you can easily extract the last segment from a path or URL in your JavaScript applications.
tags: [“JavaScript”, “path extraction”, “URL extraction”]