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.

2
  • 1
    I wonder if it really is the purpose to have an answer on StackOverflow for every possible separator character... Commented May 28, 2016 at 13:47
  • You want to get path or filename? Commented May 28, 2016 at 13:52

2 Answers 2

2

You can do it without regular expressions:

var filename = string.split('/').pop();
// "somefile.html"
Sign up to request clarification or add additional context in comments.

3 Comments

@anubhava. The backticks are called string literals, and they don't need parentheses to execute the function.
Yes I know but are all browsers supporting them?
I'd say modern browsers yes, but you are right, better to avoid them by now.
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"

4 Comments

I updated my question. Would need to only replace the path without affecting the file.
@JudsonTerrell Isn't that was it does?
So you could have infinite levels with your solution it seems?
@JudsonTerrell The regex removes all up to and including the last slash.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.