-1

I have the following code:

var fileName = "C:\fakepath\a.jpg";
fileName = fileName.replace(/.*(\/|\\)/, '')

and this will return just the a.jpg as intended but I don't understand how it knew to replace the the characters between both of "\" such as the substring "fakepath". From what I see it should just replace the first character "C" because of the period and then any appearances of "/" or "\" with "".

Schwarz
  • 395
  • 4
  • 18
  • 1
    http://regexper.com/ – epascarello Nov 12 '15 at 19:59
  • 1
    `.*` is greedy to it matches longest string before last \ – anubhava Nov 12 '15 at 20:00
  • 1
    @anubhava said it all. Regular expressions are greedy. They will match the longest possible chain of characters that satisfies the regex. According to this regex, it will match the longest string that ends with either "\" or "/". That's why "a.jpg" is returned. – Jodevan Nov 12 '15 at 20:01

1 Answers1

1

The . means any character.

The * means zero or more.

So .* matches from the start of the string to the point where matching any more characters would prevent the rest of the regular expression from matching anything.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335