/

How to extract the last segment from a path or URL using JavaScript

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:

  1. We define a thePath string that represents the path or URL, such as /Users/Flavio/Desktop.
  2. By calling lastIndexOf('/') on thePath, we find the index of the last occurrence of the forward slash (/) character.
  3. 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).
  4. Finally, we assign the extracted segment to the lastItem variable.

If you prefer a reusable function, you can create one like this:

1
2
3
4
5
6
7
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.

Screenshot

tags: [“JavaScript”, “path extraction”, “URL extraction”]