While working on a project, I had the need to get the last segment of a path.
在进行项目时,我需要获取路径的最后一部分。
In this case it was a filesystem path, but this would work also for URLs.
在这种情况下,它是一个文件系统路径,但这对于URL也适用。
This is the JavaScript code I used:
这是我使用JavaScript代码:
const lastItem = thePath.substring(thePath.lastIndexOf('/') + 1)
How does this work?
这是如何运作的?
The thePath
string contains a path. Like /Users/Flavio/Desktop
, for example.
thePath
字符串包含一个路径。 例如/Users/Flavio/Desktop
。
We identify the index of the last /
in the path, calling lastIndexOf('/')
on the thePath
string.
我们在路径字符串上调用lastIndexOf('/')
来thePath
路径中最后一个/
的索引。
Then we pass that to the substring()
method we call on the same thePath
string.
然后,将其传递给在相同thePath
字符串上调用的substring()
方法。
This will return a new string that starts from the position of the last /
, + 1 (otherwise we’d also get the /
back).
这将返回一个新字符串,该字符串从最后一个/
,+ 1的位置开始(否则我们也将获得/
)。
Finally, we assign that string to lastItem
.
最后,我们将该字符串分配给lastItem
。
You can make a simple function for it, too:
您也可以为其创建一个简单的函数:
const getLastItem = thePath => thePath.substring(thePath.lastIndexOf('/') + 1)
getLastItem('/Users')
getLastItem('/Users/Flavio')
getLastItem('/Users/Flavio/test.jpg')
getLastItem('https://flavicopes.com/test')
翻译自: https://flaviocopes.com/how-to-get-last-item-path-javascript/