Lightheaded Lightheaded - 9 months ago 66
Javascript Question

TableSorter doesn't recognize numbers

I have these two examples, which both use the same code but different sources of tablesorter. However one of them works as the other one doesn't.

$("table").tablesorter(); (doesn't work) (works)

It should first sort by percent and then by users. However it doesn't recognize the second number to be a number. I have a similar situation on my site. What could be the issue? I'm using 2.14.4 min on my site as well.

Answer Source

Upgrade to a more recent version of table sorter. Recent version seems to parse out tokens from strings such as 99% coverage (12.08 million users) and 99% coverage (10.2 million users) and compare them one by one so strings that contain more than one number still sort out as expected (we have 10 compared with 12 in the above example).

OR: you can create a custom parser that normalizes the percentage and users; and use it:

    id: 'percentThenUsers',
    is: function (s) {
        return false;
    format: function (s) {
        // "99% coverage (12.08 million users)" gets converted to
        // "1099 1012.08" which can then be sorted as text
        var m = s.replace(/[^\d\.]/g, " ").replace(/ +/g, " ").split(" ");
        return (+m[0] + 1000) + " " + (+m[1] + 1000);
    type: 'text'

$(function () {
        debug: true,
        headers: {
            0: { sorter: 'percentThenUsers' }

Demo here