英文:
How to leave the last two strings of the path?
问题
我需要保留斜杠之间的最后两个字符串。例如,/first/second/third/
想要得到 /second/third/
或 /first/second/third/fourth/
想要得到 /third/fourth/
。我认为可以使用 regex
,但不确定是否比 split
更快。有什么更好的方法来实现这个目标。
英文:
I have urls that I need to keep only the last two strings between slashes.
For ex,
/first/second/third/
want to have /second/third/
or /first/second/third/fourth/
want to have /third/fourth/
.
I think use regex
, but wonder if it's faster then split
.
What is the better way to achieve it.
答案1
得分: 1
If you go the split route, you might have to do some splicing together of the various components. You could try a regex split, but I might go for regex match here:
var input = "/first/second/third/fourth/";
var output = input.match(/(?:\/[^\/]+){2}\/$/)[0];
console.log(output);
英文:
If you go the split route, you might have to do some splicing together of the various components. You could try a regex split, but I might go for regex match here:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var input = "/first/second/third/fourth/";
var output = input.match(/(?:\/[^\/]+){2}\/$/)[0];
console.log(output);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论