Renaud is Not Bill Gates
Renaud is Not Bill Gates

Reputation: 2084

get only the name of the selected input file

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 ?

Upvotes: 0

Views: 76

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382464

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];

Upvotes: 3

Related Questions