如何对字母数字字符串值进行排序? [英] How to sort a alphanumeric string value?

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

问题描述

这里我正在使用javascript对字母数字字符串值进行排序.但是它仅对字符串进行排序.我需要的是从字符串中拆分数字值并对数字值进行排序.这是我的代码

Here i am sorting a alphanumeric string value using javascript.But it sorts the string alone.What i need is to split the numeric values from the string and sort the numeric values.Here is my code

 function sortUnorderedList(ul, sortDescending) {
        if (typeof ul == "string")
            ul = document.getElementById(ul);

        var lis = ul.getElementsByTagName("li");
        var vals = [];
        for (var i = 0, l = lis.length; i < l; i++)
            vals.push(lis[i].innerHTML);

        vals.sort();

        if (sortDescending)
            vals.reverse();

        for (var i = 0, l = lis.length; i < l; i++)
            lis[i].innerHTML = vals[i];
    }

有什么建议吗?

编辑:当前结果

PPG 101
PPG 102
PPG 57
PPG 58
PPG 99

预期结果:

PPG 57
PPG 58
PPG 99
PPG 101
PPG 102

推荐答案

要执行数字排序,必须在调用sort方法时将函数作为参数传递.

To perform a numeric sort, you must pass a function as an argument when calling the sort method.

vals.sort(function(a, b) { 
    return (a-b);
});

请参见 http://www.javascriptkit.com/javatutors/arraysort.shtml 了解更多详情

这篇关于如何对字母数字字符串值进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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