问题描述
我正在寻找一种最简单的方法来排序由数字和文本组成的数组,以及这些数组的组合。
I'm looking for the easiest way to sort an array that consists of numbers and text, and a combination of these.
例如
'123asd'
'19asd'
'12345asd'
'asd123'
'asd12'
变成
'19asd'
'123asd'
'12345asd'
'asd12'
'asd123'
这将与。
排序功能本身有效,我是什么need是一个可以说'19asd'小于'123asd'的函数。
The sorting function in itself works, what I need is a function that can say that that '19asd' is smaller than '123asd'.
我用JavaScript写这个。
I'm writing this in JavaScript.
编辑:正如 adormitu 指出的那样,我正在寻找的是一个自然排序功能
as adormitu pointed out, what I'm looking for is a function for natural sorting
推荐答案
现在可以在使用localeCompare的现代浏览器中实现。通过传递 numeric:true
选项,它将巧妙地识别数字。您可以使用 sensitivity:'base'
来区分大小写。在Chrome,Firefox和IE11中测试过。
This is now possible in modern browsers using localeCompare. By passing the numeric: true
option, it will smartly recognize numbers. You can do case-insensitive using sensitivity: 'base'
. Tested in Chrome, Firefox, and IE11.
以下是一个示例。它返回 1
,意味着10在2之后:
Here's an example. It returns 1
, meaning 10 goes after 2:
'10'.localeCompare( '2',undefined,{numeric:true,sensitivity:'base'})
对于排序大量字符串时的性能,文章说:
For performance when sorting large numbers of strings, the article says:
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
var myArray = ['1_Document', '11_Document', '2_Document'];
console.log(myArray.sort(collator.compare));
这篇关于Javascript:自然的字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!