Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Tablesorter - sorting alphanumeric columns

I'm trying to sort a column that contains alphanumeric data e.g.

  • sometext1
  • sometext2
  • sometext3
  • sometext10

unfortunately Tablesorter doesn't sort correctly i.e.

  • sometext1
  • sometext10
  • sometext2
  • sometext3

Any help would be most appreciated. Thanks!

like image 308
benjamunky Avatar asked Aug 10 '26 17:08

benjamunky


2 Answers

The solution:

    $.tablesorter.addParser({
      id: 'alphanum',
      is: function(s) {
        return false;
      },
      format: function(s) {
        var str = s.replace(/(\d{1,2})/g, function(a){
            return pad(a);
        });

        return str;
      },
      type: 'text'
    });

    function pad(num ){
      var s = '00000' + num;
      return s.substr(s.length-5);
    }    
like image 81
benjamunky Avatar answered Aug 12 '26 11:08

benjamunky


http://tablesorter.com/docs/example-parsers.html

So, this example shows you how to create your own ordering logic.Look at the function:

    format: function(s) { 
        // format your data for normalization 
        return s.toLowerCase().replace(/good/,2).replace(/medium/,1).replace(/bad/,0); 
    }, 

You need to write a javascript function to get the text and numeric portions of your string "sometext3" and then format the number with zero padding "sometext00000003" this would fix your sorting issue and will not change how it's displayed in the client.

Here's a rudimentary example:

<script>
function normalizeAlphaNumeric(text) {
r = new RegExp("([^\\d]*)(\\d*)");
var match = r.exec(text);
    return match[1] + pad(match[2]);
}

function pad(num) {
    var s = "000000000" + num;
    return s.substr(s.length-8); // i chose 8
}

document.write(normalizeAlphaNumeric("sometext1") + "<br/>");
document.write(normalizeAlphaNumeric("sometext2")+ "<br/>");
document.write(normalizeAlphaNumeric("sometext3")+ "<br/>");
document.write(normalizeAlphaNumeric("sometext10")+ "<br/>");

</script>

The output of this is:

sometext00000001
sometext00000002
sometext00000003
sometext00000010

Which is sortable now.

like image 38
Trever Shick Avatar answered Aug 12 '26 11:08

Trever Shick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!