Javascript sort string numeric-alpha with zeroes at end
I'm terrible with math, but I need to be able to sort a string in JavaScript (or jQuery) in numeric-alpha order with zeroes at the end.
So to do this, I know I can convert the string into an array with myStr.split('') and then call sort() with a custom sort function, so here is what I have so far:
function mysort(a, b) {
// not sure what to put here.
// order should be: 123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0
}
function sortMyString(str) {
str.split('');
return str.sort(mysort);
}
I would really appreciate help on this.
Th开发者_开发技巧ank you.
This will result in the string being the same as above, feel free to mix the string up, add more etc and it should come up in the order you want.
http://jsfiddle.net/dJMHK/
var str = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0';
str = str.split('');
str = str.sort(function (a,b) {
if (a === '0' || b === '0')
return (b === a) ? 0 : (a < b) ? 1 : -1;
return (a < b) ? -1 : (a === b) ? 0 : 1;
});
document.write(str);
If you're splitting and comparing individual characters you can use the charCodeAt function.
a.charCodeAt(0)
and
b.charCodeAt(0)
to get the unicode character value. You'll want to have cases for 1-9, A-Z, a-z, 0, and anything you weren't planning for.
In your sort function, to get items in the appropriate order: return 0 if a == b, 1 if a > b, and -1 if a < b. Let me know if you need help working on the sort function, this is all I have time to guide you on at the moment.
You can use the sort function then handle the zeros with some custom code. Here is a reference:
http://www.w3schools.com/jsref/jsref_sort.asp
精彩评论