Javascript:自然排序的字母数字字符串 [英] Javascript : natural sort of alphanumerical strings

查看:34
本文介绍了Javascript:自然排序的字母数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找对由数字和文本以及它们的组合组成的数组进行排序的最简单方法.

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'

这将与 我在这里问的另一个问题.

排序函数本身是有效的,我需要的是一个可以说'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 选项,它将智能地识别数字.您可以使用 sensitive: '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:

在比较大量字符串时,例如对大型数组进行排序时,最好创建一个 Intl.Collat​​or 对象并使用其 compare 属性提供的函数.文档链接

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare property. Docs link

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:自然排序的字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆