忽略DataTables排序的数字中的非数字字符

时间:2016-10-28 18:57:50

标签: datatables datatables-1.10

我正在为DataTables创建一个自定义排序插件,它将对包含非数字行的数字列进行排序。我得到的部分是“N / A'在底部的行但似乎无法弄清楚,如何使它忽略数字中的逗号。

例如:

$ 12,443.00
362123231个
N / A
N / A

34,242.42
23234个

以下代码设法忽略除数字中逗号之外的所有内容。

代码:

function numeric_sort(a, b, high) {
    var reg = /[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?[0-9]+)?/;
    a = a.match(reg);
    a = a !== null ? parseFloat(a[0]) : high;
    b = b.match(reg);
    b = b !== null ? parseFloat(b[0]) : high;
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}

jQuery.extend( jQuery.fn.dataTableExt.oSort, {
    "numeric-empty-bottom-asc": function (a, b) {
        return numeric_sort(a, b, Number.POSITIVE_INFINITY);
    },
    "numeric-empty-bottom-desc": function (a, b) {
        return numeric_sort(a, b, Number.NEGATIVE_INFINITY) * -1;
    }
} );

我从以下代码获得了代码:http://jsfiddle.net/6qmkY/

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以使用replace()删除逗号。

function sortNumbersIgnoreText(a, b, high) {
    var reg = /[+-]?((\d+(\.\d*)?)|\.\d+)([eE][+-]?[0-9]+)?/;    
    a = a.replace(/,/g, '');
    a = a.match(reg);      
    a = a !== null ? parseFloat(a[0]) : high;
    b = b.replace(/,/g, '');
    b = b.match(reg);    
    b = b !== null ? parseFloat(b[0]) : high;
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));    
}

请参阅updated jsFiddle以获取代码和演示。

答案 1 :(得分:-1)

您可以替换所有非数字字符,包括逗号(不包括小数)。

function sortNumbersIgnoreText(a, b, high) {
    a = a.replace(/[^0-9\.]+/g, '');
    a = (a !== null && a !== '') ? parseFloat(a) : high;
    b = b.replace(/[^0-9\.]+/g, '');
    b = (b !== null && b !== '') ? parseFloat(b) : high;
    return ((a < b) ? -1 : ((a > b) ? 1 : 0));    
}