如何使用JavaScript获取路径或URL的最后一段

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/

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值