How to get the last paragraph of a path or URL using JavaScript

When working on a project, I need to get the last part of the path.

In this case, it is a file system path, but this also applies to URLs.

This is the JavaScript code I used:

const lastItem = thePath.substring(thePath.lastIndexOf('/') + 1)

How does this work?

ThisthePathThe string contains the path. like/Users/Flavio/Desktop, E.g.

We determine the index of the last one/On the road, calllastIndexOf('/')inthePathString.

Then we pass it tosubstring()We call the same methodthePathString.

This will return a new string starting from the last position/, + 1 (otherwise we’d also get the /Back).

Finally, we assign the string tolastItem.

You can also create a simple function for it:

const getLastItem = thePath => thePath.substring(thePath.lastIndexOf('/') + 1)

getLastItem(’/Users’) getLastItem(’/Users/Flavio’) getLastItem(’/Users/Flavio/test.jpg’) getLastItem(

Download mine for freeJavaScript beginner's manual

More js tutorials: