3

Hello i need to match filnames with extensions.

Problem is that paths could be both unix and windows, so seperated by / or \ also unix allows . in filenames, so t.est.txt also should be matched.

My code :

var regex = new RegExp('[\\/]?([/\w+.]+/\w+)/\s*$');
var value = this.attachment.fileInput.dom.value;
console.log(value.match(regex));
console.log(regex.exec(value));

this regex works fine in rubular. But for some reason ie, chrome and firefox does not match any string and returns null.

3

3 Answers 3

9

You could just grab whatever's at the end following the last \ or /, such as:

var file = str.match(/[^\\/]+$/)[0];

(Remember files don't always need extensions)

Though if you really want to force extension matching:

var file = str.match(/[^\\/]+\.[^\\/]+$/)[0];
Sign up to request clarification or add additional context in comments.

1 Comment

In my case it always has extensions. Thanks, second one works perfect
6

Try the following syntax:

var filename = (value.match(/[^\\/]+\.[^\\/]+$/) || []).pop();

It should work fine for the following examples:

"path/to/file.ext"     --> "file.ext"
"path\\to\\file.ext"   --> "file.ext"
"path/to/file.ext.txt" --> "file.ext.txt"
"path/to/file"         --> ""

Comments

3

Credits go to RegeBuddy's library for this snippet:

if (/[^\\\/:*?"<>|\r\n]+$/im.test(js)) {
    // Successful match
} else {
    // Match attempt failed
}

1 Comment

Good! Windows says \/:*?"<>| can not be filled in a file name.

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.