Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 653
kuldarim Avatar asked Jun 10 '26 19:06

kuldarim


1 Answers

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];
like image 84
MDEV Avatar answered Jun 12 '26 10:06

MDEV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!