I am currently using Mottie's version of tablesorter to build a directory. I have a field of name (combines firstname and lastname) in the same table cell. Most data entries are simple (Firstname LastName), I have the code set up so that it sorts by swapping the last and first name using:
textExtraction: {
0: function(node) {
// swap first and last name for sorting
return $.trim($(node).text() || '').replace(/(\w+)\s(\w+)/g,'$2 $1');
}
}
Unfortuntately, there are a few people who have a preferred first name and will appear in the table like:
[FirstName (PreferredName) LastName]
which the sorting ends up sorting by just the first name.
For example it sorts like this:
Alex Adams
Robert (Bob) Rover
Bruce Black
Catelyn Cruz
Adam (Dave) Francis
Elaine Evans
But I would like it to just use last name such as:
Alex Adams
Bruce Black
Catelyn Cruz
Elaine Evans
Adam (Dave) Francis
Robert (Bob) Rover
I don't really have a full grasp on regex so I'm unsure if there is a simple way to make it so that it always sorts on the Lastname.
Any help (including a bit of an explanation on how this replace.(regex) is working, would be greatly appreciated!
Thank you!
I wouldn't use the textExtraction
method since it applies to ALL table cells.
Instead, try this parser. It uses array manipulation to move the last name to the front (demo)
$(function() {
$.tablesorter.addParser({
id: 'last-name',
is: function() {
return false;
},
format: function(str) {
var parts = (str || '').split(/\s+/),
last = parts.pop();
parts.unshift(last);
return parts.join(' ');
},
// set type, either numeric or text
type: 'text'
});
$('table').tablesorter({
theme: 'blue'
});
});
Don't forget to add the class name to set the parser:
<th class="sorter-last-name">Name</th>