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
- s开发者_运维知识库ometext3
Any help would be most appreciated. Thanks!
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);
}
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.
精彩评论