kuldarim
kuldarim

Reputation: 1106

Javascript regex match filename with extension

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.

Upvotes: 3

Views: 18713

Answers (3)

Zathrus Writer
Zathrus Writer

Reputation: 4331

Credits go to RegeBuddy's library for this snippet:

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

Upvotes: 3

MDEV
MDEV

Reputation: 10838

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

Upvotes: 9

VisioN
VisioN

Reputation: 145368

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"         --> ""

Upvotes: 6

Related Questions