numString

Sorting for number value that is included anywhere in a regex.

This plug in will sort only on the number value that is included anywhere in a Regex. This is useful for sorting data which requires some extra context to be included in the table.

Plug-in code

$.fn.dataTable.numString = function(format) {
    //This is the type detection plug in
    $.fn.dataTable.ext.type.detect.unshift(function(data) {
      if (typeof data !== "string") {
        return null;
      }
  
      if (data.match(format)) {
        return "numString-" + format.source;
      }
  
      return null;
    });
    
    //This is the ordering plug in
    $.fn.dataTable.ext.type.order[
      "numString-" + format.source + "-pre"
    ] = function(data) {
      var num = data.replace(/\D/g, "");
  
      return num * 1;
    };
    // end plug-in
  };

CDN

This plug-in is available on the DataTables CDN:

JS

Note that if you are using multiple plug-ins, it is beneficial in terms of performance to combine the plug-ins into a single file and host it on your own server, rather than making multiple requests to the DataTables CDN.

Version control

If you have any ideas for how this plug-in can be improved, or spot anything that is in error, it is available on GitHub and pull requests are very welcome!

Examples

//This example shows a mixture of text and number values, with the number at the start of the expression.
//It is using regex and start and end of expression tags.
//It will match "5 examples completed." for example.
$(document).ready( function(){
    $.fn.dataTable.numString(/^\d+ examples? completed.$/);
    var table = $('#example').DataTable();
})
//This example shows a mixture of text and number values, with the number at the end of the expression.
//It is using regex and start and end of expression tags.
//It will match "Examples left: 67" for example.
$(document).ready( function(){
    $.fn.dataTable.numString(/^Examples? left: \d+$/);
    var table = $('#example').DataTable();
})
//This example shows a mixture of text and number values, with the number in the middle of the expression.
//It is using regex and no start and end of expression tags.
//It will match "Only 1 left." for example.
$(document).ready(function(){
    $.fn.dataTable.numString(/Only \d+ left./);
    var table = $('example').DataTable();
})