离开路径的最后两个字符串。

huangapple go评论75阅读模式
英文:

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 = &quot;/first/second/third/fourth/&quot;;
var output = input.match(/(?:\/[^\/]+){2}\/$/)[0];
console.log(output);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月10日 14:51:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215628.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定