我正在尝试删除路径的第一部分:'/some/string/is/here' => '/string/is/here'我试过了:'/some/string/is/here'.split('/').slice(2).join('/') = string/is/here但这也删除了第一个斜线。有没有办法删除路径的第一部分并保留第一个斜杠?
2 回答

慕斯709654
TA贡献1840条经验 获得超5个赞
如果你保证有一个前导斜杠,那么只需添加斜杠:
'/' + '/some/string/is/here'.split('/').slice(2).join('/')
如果不能保证有前导斜杠,则可以使用正则表达式:
'/some/string/is/here'.match(/^\/?[^\/]+((?:\/[^\/]+)+)$/)[1]
// or
'/some/string/is/here'.replace(/^\/?[^\/]+/, "")
或者,您可以在第二个斜杠上切片:
const str = '/some/string/is/here';
str.slice(str.indexOf("/", 1))

FFIVE
TA贡献1797条经验 获得超6个赞
也许你可以这样做:
const myString = '/some/string/is/here';
console.log("/" + myString.replace(/^.+?[/]/, ''));
添加回答
举报
0/150
提交
取消