diff --git a/dataRender/ellipsis.js b/dataRender/ellipsis.js index 117b834..110073f 100644 --- a/dataRender/ellipsis.js +++ b/dataRender/ellipsis.js @@ -9,7 +9,7 @@ * This function should be used with the `dt-init columns.render` configuration * option of DataTables. * - * It accepts two parameters: + * It accepts three parameters: * * 1. `-type integer` - The number of characters to restrict the displayed data * to. @@ -17,6 +17,8 @@ * of the string should not occur in the middle of a word (`true`) or if it * can (`false`). This can allow the display of strings to look nicer, at the * expense of showing less characters. + * 2. `-type boolean` (optional - default `false`) - Escape HTML entities + * (`true`) or not (`false` - default). * * @name ellipsis * @summary Restrict output data to a particular length, showing anything @@ -45,31 +47,43 @@ * } ); */ -jQuery.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak ) { - return { - display: function ( d ) { - if ( wordbreak === undefined ) { - wordbreak = false; - } +jQuery.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) { + var esc = function ( t ) { + return t + .replace( /&/, '&' ) + .replace( //, '>' ) + .replace( /"/, '"' ); + }; - if ( typeof d !== 'number' && typeof d !== 'string' ) { - return d; - } + return function ( d, type, row ) { + // Order, search and type get the original data + if ( type !== 'display' ) { + return d; + } - var str = d.toString(); // cast numbers + if ( typeof d !== 'number' && typeof d !== 'string' ) { + return d; + } - if ( d.length < cutoff ) { - return d; - } + d = d.toString(); // cast numbers - str = d.substr(0, cutoff); + if ( d.length < cutoff ) { + return d; + } - if ( wordbreak ) { - // Find the last white space character in the string - str = str.replace(/\s([^\s]*)$/, ''); - } + var shortened = d.substr(0, cutoff-1); - return ''+str+'…'; + // Find the last white space character in the string + if ( wordbreak ) { + shortened = shortened.replace(/\s([^\s]*)$/, ''); } + + // Protect against uncontrolled HTML input + if ( escapeHtml ) { + shortened = esc( shortened ); + } + + return ''+shortened+'…'; }; -}; \ No newline at end of file +};