How can I catch everything after the underscore in

2019-08-23 16:48发布

How can I catch everything after the last underscore in a filename?

ex: 24235235adasd_4.jpg into 4.jpg

Thanks again!

4条回答
劫难
2楼-- · 2019-08-23 16:57
var end = filename.replace(/.*_/,'');
查看更多
趁早两清
3楼-- · 2019-08-23 16:58
var foo = '24235235adasd_4.jpg';
var bar = foo.substr(foo.lastIndexOf('_') + 1);

*Make a note to yourself that this wont work with those uncommon files that have an '_' in their extension (for example, I've seen some that are named filename.tx_)

查看更多
可以哭但决不认输i
4楼-- · 2019-08-23 17:00
var end = "24235235adasd_4.jpg".match(/.*_(.*)/)[1];

Edit: Whoops, the ungreedy modifier was wrong.

Edit 2: After running a benchmark, this is the slowest method. Don't use it ;) Here is the benchmark and the results.

Benchmark:

var MAX     = 100000,     i =  0, 
    s       = new Date(), e = new Date(), 
    str     = "24235235ad_as___4.jpg",
    methods = {
        "Matching":  function() { return str.match(/.*_(.*)/)[1];               },
        "Substr":    function() { return str.substr(str.lastIndexOf('_') + 1);  },
        "Split/pop": function() { return str.split('_').pop();                  },
        "Replace":   function() { return str.replace(/.*_/,'');                 }
    };

console.info("Each method over %d iterations", MAX);
for ( var m in methods ) {
    if ( !methods.hasOwnProperty(m) ) { continue; }
    i = 0;

    s = new Date();
    do {
        methods[m]();
    } while ( ++i<MAX );
    e = new Date();

    console.info(m);
    console.log("Result: '%s'", methods[m]());
    console.log("Total: %dms; average: %dms", +e - +s, (+e - +s) / MAX);
}

Results:

Each method over 100000 iterations
Matching
Result: '4.jpg'
Total: 1079ms; average: 0.01079ms
Substr
Result: '4.jpg'
Total: 371ms; average: 0.00371ms
Split/pop
Result: '4.jpg'
Total: 640ms; average: 0.0064ms
Replace
Result: '4.jpg'
Total: 596ms; average: 0.00596ms

Gordon Tucker's Substr/lastIndexOf is the fastest by a long shot.

查看更多
ら.Afraid
5楼-- · 2019-08-23 17:03
"24235235adasd_4.jpg".split('_').pop();
查看更多
登录 后发表回答