I'm currently rewriting the userlist implementation in an IM client interface that uses JavaScript. The names in this list are currently sorted alphabetically, and I want to edit this so that it only takes alphabetical characters in account when paring strings.
For instance: "1foo" es after "bar", because "foo" es after "bar".
I know I could just create two temporary strings by removing all non-alphabetical characters from the two original strings, but I'm guessing that there must be easier ways to do this.
I'm currently rewriting the userlist implementation in an IM client interface that uses JavaScript. The names in this list are currently sorted alphabetically, and I want to edit this so that it only takes alphabetical characters in account when paring strings.
For instance: "1foo" es after "bar", because "foo" es after "bar".
I know I could just create two temporary strings by removing all non-alphabetical characters from the two original strings, but I'm guessing that there must be easier ways to do this.
Share Improve this question asked Jan 23, 2012 at 22:13 NekoNeko 3,7548 gold badges30 silver badges34 bronze badges 4- Can you post the code you're currently using to sort? – j08691 Commented Jan 23, 2012 at 22:15
- Do you want the strings starting with numbers sorted before or after strings with letters? What do you want to happen? – mowwwalker Commented Jan 23, 2012 at 22:15
- You can use custom sort functions in javascript: javascriptkit./javatutors/arraysort.shtml – mowwwalker Commented Jan 23, 2012 at 22:15
- I'd just use a regex to get only alphabetic chars and pare those. I believe that there are some callback versions of the string find functions that could be used too. – Robert Commented Jan 23, 2012 at 22:16
1 Answer
Reset to default 8Well, if you have an array of strings called arr
, you can use this one-liner:
arr.sort(function(a,b) {return a.replace(/[^a-z]/ig,'') > b.replace(/[^a-z]/ig,'') ? 1 : -1;});
arr
is now sorted taking only letters into account.