JavaScript regex to capture everything after the second to last backslash - Stack Overflow

I have a regex that looks like the following currently:^.*[\]This will strip every single backslas

I have a regex that looks like the following currently:

/^.*[\\\/]/

This will strip every single backslash from a string. The problem I'm facing is I have to now be able to capture everything from the second to last backslash.

Example:

/Users/foo/a/b/c would return b/c /Another/example/ would return Another/Example

So I need to capture everything after the second to last backslash. How would the regex above do that?

I have a regex that looks like the following currently:

/^.*[\\\/]/

This will strip every single backslash from a string. The problem I'm facing is I have to now be able to capture everything from the second to last backslash.

Example:

/Users/foo/a/b/c would return b/c /Another/example/ would return Another/Example

So I need to capture everything after the second to last backslash. How would the regex above do that?

Share Improve this question asked Feb 7, 2017 at 0:28 randombitsrandombits 48.6k79 gold badges273 silver badges449 bronze badges 4
  • Wouldn't you want to get a/b from your first example if you're capturing everything around the second-to-last backslash? Not super-clear... – Nightfirecat Commented Feb 7, 2017 at 0:32
  • are your urls/strings consistently employing trailing slashes? or should they be ignored? – haxxxton Commented Feb 7, 2017 at 0:39
  • @haxxxton they can actually be ignored. – randombits Commented Feb 7, 2017 at 0:41
  • can we assume that the characters between the / are word characters (ie. [a-zA-Z0-9_]) are there other characters that need to be acmodated for (e.g. $-_.+!*'(),)? – haxxxton Commented Feb 7, 2017 at 1:08
Add a ment  | 

3 Answers 3

Reset to default 8

Try with this simple solution:

s = "aaaa/bbbb/cccc/dddd";
s.split("/").slice(-2).join("/"); /* It will return "cccc/dddd" */

I assume that you mean forward slash, not backslash.

Here is a regex alternative to pierlauro's answer.

/([^\/]+\/[^\/]+)\/?$/

Regex101

As pierlauro's answer shows, split, join, and slice are probably the best options for this. But if you MUST use a regex (not sure why), you could employ something like the following:

\/?(\[^\/\]+?\/\[^\/\]+)\/?$

This regex acmodates for optional trailing slashes and for urls shorter than 2 /s. It leverages the $ character to focus our search scope on the end of the string.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745323377a4622545.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信