How Can I Catch Everything After The Underscore In A Filepath With Javascript?
How can I catch everything after the last underscore in a filename? ex: 24235235adasd_4.jpg into 4.jpg Thanks again!
Solution 1:
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_
)
Solution 2:
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:
varMAX = 100000, i = 0,
s = newDate(), e = newDate(),
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 = newDate();
do {
methods[m]();
} while ( ++i<MAX );
e = newDate();
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.
Solution 3:
"24235235adasd_4.jpg".split('_').pop();
Solution 4:
var end = filename.replace(/.*_/,'');
Post a Comment for "How Can I Catch Everything After The Underscore In A Filepath With Javascript?"