var chunkRgx = /(_+)|([0-9]+)|([^0-9_]+)/g;
function naturalCompare(a, b) {
var ax = [], bx = [];
a.replace(chunkRgx, function(_, $1, $2, $3) {
ax.push([$1 || "0", $2 || Infinity, $3 || ""])
});
b.replace(chunkRgx, function(_, $1, $2, $3) {
bx.push([$1 || "0", $2 || Infinity, $3 || ""])
});
while(ax.length && bx.length) {
var an = ax.shift();
var bn = bx.shift();
var nn = an[0].localeCompare(bn[0]) ||
(an[1] - bn[1]) ||
an[2].localeCompare(bn[2]);
if(nn) return nn;
}
return ax.length - bx.length;
}
/////////////////////////
test = [
"img12.png",
"img10.png",
"img2.png",
"img1.png",
"img101.png",
"img101a.png",
"abc10.jpg",
"abc10",
"abc2.jpg",
"20.jpg",
"20",
"abc",
"abc2",
"_abc",
"_ab_c",
"_ab__c",
"_abc_d",
"ab_",
"abc_",
"_ab_cd",
""
];
test.sort(naturalCompare)
document.write("<pre>" + JSON.stringify(test,0,3));