Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  122] [ 5]  / answers: 1 / hits: 74357  / 13 Years ago, wed, january 25, 2012, 12:00:00

I'm sure this must be easy enough, but I'm struggling...



var regexFileName = /[^\]*$/; // match filename
var regexFileExtension = /(w+)$/; // match file extension

function displayUpload() {
var path = $el.val(); //This is a file input
var filename = path.match(regexFileName); // returns file name
var extension = filename[0].match(regexFileExtension); // returns extension

console.log(The filename is + filename[0]);
console.log(The extension is + extension[0]);
}


The function above works fine, but I'm sure it must be possible to achieve with a single regex, by referencing different parts of the array returned with the .match() method. I've tried combining these regex but without success.



Also, I'm not using a string to test it on in the example, as console.log() escapes the backslashes in a filepath and it was starting to confuse me :)


More From » jquery

 Answers
76

Assuming that all files do have an extension, you could use



var regexAll = /[^\]*.(w+)$/;


Then you can do



var total = path.match(regexAll);
var filename = total[0];
var extension = total[1];

[#87813] Monday, January 23, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
diane

Total Points: 264
Total Questions: 104
Total Answers: 95

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;