How to get the file name from a full path using JavaScript?

前端 未结 18 974
生来不讨喜
生来不讨喜 2020-11-22 11:01

Is there a way that I can get the last value (based on the \'\\\' symbol) from a full path?

Example:

C:\\Documents and Settings\\img\\recycled log.jpg<

18条回答
  •  悲哀的现实
    2020-11-22 11:33

    Just for the sake of performance, I tested all the answers given here:

    var substringTest = function (str) {
        return str.substring(str.lastIndexOf('/')+1);
    }
    
    var replaceTest = function (str) {
        return str.replace(/^.*(\\|\/|\:)/, '');
    }
    
    var execTest = function (str) {
        return /([^\\]+)$/.exec(str)[1];
    }
    
    var splitTest = function (str) {
        return str.split('\\').pop().split('/').pop();
    }
    
    substringTest took   0.09508600000000023ms
    replaceTest   took   0.049203000000000004ms
    execTest      took   0.04859899999999939ms
    splitTest     took   0.02505500000000005ms
    

    And the winner is the Split and Pop style answer, Thanks to bobince !

提交回复
热议问题