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 ?

3
  • Could you clarify what kind of output you are expecting for a given input? An example would be great. Commented Apr 21, 2016 at 14:53
  • You can try Regex101 wich is a great regex tester. Commented Apr 21, 2016 at 14:54
  • OP, please never just link to your code, write the relevant part in your question. Commented Apr 21, 2016 at 14:58

1 Answer 1

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.