0

I need a regex that would replace something like this but leave the file name.

/folder1/folder2/folder3/anything/somefile.html

Also could someone show me how to implement this with replace method? Replacing the entire path match to empty string and again leaving the file and which would be anything.

Thanks in advance.

Judson Terrell
  • 4,204
  • 2
  • 29
  • 45

2 Answers2

2

You can do it without regular expressions:

var filename = string.split('/').pop();
// "somefile.html"
anubhava
  • 761,203
  • 64
  • 569
  • 643
Washington Guedes
  • 4,254
  • 3
  • 30
  • 56
1

You can use .*\/.

. will match anything
* will repeat the previous zero or more times.
\/ is a literal slash (/). But needs to be escaped because it's part of the regex construct:

var str = '/folder1/folder2/folder3/anything/somefile.html';
str.replace(/.*\//, ''); // "somefile.html"
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123