TypeScript中如何按字符串最后一个/使用split方法分割?
按最后一个斜杠分割字符串的解决方案
你可以通过lastIndexOf()定位最后一个/的位置,再结合字符串截取方法实现需求,比直接用split()更精准,代码如下:
let url = "https://learn.edu/d2l/login?sessionExpired=1&target=%2fd2l%2fhome"; const lastSlashIndex = url.lastIndexOf("/"); const beforeLastSlash = url.substring(0, lastSlashIndex); const afterLastSlash = url.substring(lastSlashIndex + 1); console.log(beforeLastSlash); // 输出 "https://learn.edu/d2l/login?sessionExpired=1&target=%2fd2l" console.log(afterLastSlash); // 输出 "home"
为什么原来的方法不生效?
- 直接用
url.split("/")会把所有斜杠都分割成数组,你用let beforeLastSlash, afterLastSlash = ...的赋值方式,只会把数组第一个元素给beforeLastSlash、第二个给afterLastSlash,完全不符合“按最后一个分割”的需求。 split的limit参数是限制返回数组的长度,比如split("/", 1)只会返回包含第一个分割部分的数组,所以afterLastSlash自然是undefined,这个参数没法帮你实现目标。
另一种简洁写法(数组操作)
如果偏好数组方法,也可以先分割成数组,再单独提取最后一项,前面的部分重新拼接:
let url = "https://learn.edu/d2l/login?sessionExpired=1&target=%2fd2l%2fhome"; const parts = url.split("/"); const afterLastSlash = parts.pop(); const beforeLastSlash = parts.join("/"); console.log(beforeLastSlash); // 同上 console.log(afterLastSlash); // 同上
注意:如果字符串末尾是/,pop()会得到空字符串,需要根据业务场景判断是否要处理这种边缘情况。
内容的提问来源于stack exchange,提问作者justchillen
相关产品推荐
相关产品推荐

