1
votes

I do use tablesorter (https://mottie.github.io/tablesorter/docs/index.html) To sort my HTML tables.

I have one sorting I cannot find howtoo. ie.

  • (4)
  • (dns)
  • 1
  • 2
  • 3
  • 5
  • dns

is to be sorted as:

  • 1
  • 2
  • 3
  • (4)
  • 5
  • (dns)
  • dns

in short: the () are to be ignored and numeric sort, numeric first then alphabetical.

I have seen how to replace characters, (doesn't work as "empty" as some rank too) The parsers I have seen thusfar require me to create per header and known value to be replaced. ie:

    $.tablesorter.addParser({ 
    id: 'nummeriek', 
    is: function(s) { 
        return false; 
    }, 
    format: function(s) { 
        // format your data for normalization 
        return s.toLowerCase().replace('dns',999).replace('(dns)',999).replace('(4)',4); 
    }, 
    type: 'numeric' 
}); 

$('.tablesorter').tablesorter({ 
        headers: { 
            6: { 
                sorter:'nummeriek' 
            } 
        } 
}); 

If I have to do this for every possible table content I end up creating hundreds of replace() statements. as I have scores from 1 to 100 Thus (1) to (100) is possible too...

There must be an easier way. Any help is much appreciated.

1

1 Answers

0
votes

The default digit parser "assumes" that numbers wrapped in parentheses are negative; this is a common method of indicating a negative number in accounting (ref).

To get around this, you will need to slightly modify the parser (demo)

$(function() {
  $.tablesorter.addParser({
    id: 'nummeriek',
    is: function(s) {
      return false;
    },
    format: function(str) {
      // format your data for normalization
      var s = str.replace(/[()]/g, ""),
        n = parseFloat(s);
      return !isNaN(n) && isFinite(n) ? n : s;
    },
    type: 'numeric'
  });

  $('.tablesorter').tablesorter({
    headers: {
      0: {
        sorter: 'nummeriek'
      }
    }
  });
});

Note: this parser always returns a non-numeric string without parentheses, e.g. "(dns)" will become "dns". I kept it this way so the "(dns)" entries will sort as if they are "dns".