I have an array like;
[\"IL0 Foo\", \"PI0 Bar\", \"IL10 Baz\", \"IL3 Bob says hello\"]
And need to sort it so it appears like;
You could do a regex like this to get non-numeric and numeric parts of the string:
var s = "foo124bar23";
s.match(/[^\d]+|\d+/g)
returns: ["foo", "124" , "bar" , "23"]
Then in your compare function you can iterate through the parts of the two strings comparing them part-by-part. The first non-matching part determines the result of the overall comparison. For each part, check if the part starts with a digit and if so parse it as a number before doing the comparison.
var re = /([a-z]+)(\d+)(.+)/i;
var arr = ["IL0 Foo", "PI0 Bar", "IL10 Baz", "IL3 Bob says hello"];
var order = arr.sort( function(a,b){
var ma = a.match(re),
mb = b.match(re),
a_str = ma[1],
b_str = mb[1],
a_num = parseInt(ma[2],10),
b_num = parseInt(mb[2],10),
a_rem = ma[3],
b_rem = mb[3];
return a_str > b_str ? 1 : a_str < b_str ? -1 : a_num > b_num ? 1 : a_num < b_num ? -1 : a_rem > b_rem;
});