0

I'm trying to get only the name of the selected file using this regex :

var regex = /.*(\/|\\)/;

but it only works in some cases, you can find the full example in this fiddle :

var regex = /.*(\/|\\)/;

var path1 = 'C:\fakepath\filename.doc'.replace(regex, ''),
    path2 = 'C:\\fakepath\\filename.doc'.replace(regex, ''),
    path3 = '/var/fakepath/filename.doc'.replace(regex, '');

How can solve this ?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191

1 Answers1

3

Your problem isn't where you think it is.

Your problem is in writing your literal string.

'C:\fakepath\filename.doc' doesn't make the \ character but the \f one (form feed).

This being said, don't use replace when you want to extract a string, but match, so that you can define what you want instead of what you don't want:

var regex = /[^\/\\]+$/;

var path1 = 'C:\\fakepath\\filename.doc'.match(regex)[0],
    path2 = 'C:\\fakepath\\filename.doc'.match(regex)[0],
    path3 = '/var/fakepath/filename.doc'.match(regex)[0];
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758