I have an array like;
[\"IL0 Foo\", \"PI0 Bar\", \"IL10 Baz\", \"IL3 Bob says hello\"]
And need to sort it so it appears like;
Pad numbers in string with leading zeros, then sort normally.
var naturalSort = function (a, b) {
a = ('' + a).replace(/(\d+)/g, function (n) { return ('0000' + n).slice(-5) });
b = ('' + b).replace(/(\d+)/g, function (n) { return ('0000' + n).slice(-5) });
return a.localeCompare(b);
}
var naturalSortModern = function (a, b) {
return ('' + a).localeCompare(('' + b), 'en', { numeric: true });
}
console.dir((["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"].sort(naturalSort)));
console.dir((["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"].sort(naturalSortModern)));