最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: How compare strings on alphabetical characters only? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 8

Well, 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.

发布评论

评论列表(0)

  1. 暂无评论