问题
I'm using datatables exactly as the example here. So to export data I used a function that allows me to change <br>
with newlines in excel.
I used this:
return column === 5 ? data.replace( /<br\s*\/?>/ig, "\n"): data;
However when I try to add a second change I want to make to a different column it doesn't work... I tried adding this right below the first working replacement:
return column === 1 ? data.replace( /<.*?>/ig, ""): data;
I want to basically strip all html tags after first changing the <br>
to newlines. But as my code is now, the second part just gets ignored during export... Does anyone know what I am doing wrong?
Here is my full code:
var fixNewLine = {
exportOptions: {
format: {
body: function ( data, column, row ) {
return column === 5 ? data.replace( /<br\s*\/?>/ig, "\n"): data;
return column === 1 ? data.replace( /<.*?>/ig, ""): data;
}
}
}
};
var t2e = $('#table2excel').DataTable({
dom: 'Bfrtip',
buttons:[
$.extend( true, {}, fixNewLine, {
extend: 'excelHtml5'
} ),
'pdf', 'print', 'copy', 'csv' //, 'excel'
]
});
回答1:
You can't have multiple return statement in code only first one will be executed, try this:
var fixNewLine = {
exportOptions: {
format: {
body: function ( data, column, row ) {
if (column === 5) {
data = data.replace(/<br\s*\/?>/ig, "\n");
}
return column === 1 ? data.replace(/<.*?>/ig, ""): data;
}
}
}
};
回答2:
A switch statement to deal with each column individually worked really well for me. See my usage below...
var fixNewLine = {
exportOptions: {
format: {
body: function ( data, row, column, node ) {
switch(column){
case 1 : return column === 1 ? data.replace(/<.*?>/ig, "") : data; break;
case 2 : return column === 2 ? data.replace(/<.*?>/ig, "") : data; break;
case 3 : return column === 3 ? data.replace(/<.*?>/ig, "") : data; break;
case 4 : return column === 4 ? data.replace(/<.*?>/ig, "") : data; break;
case 5 : return column === 5 ? data.replace(/<.*?>/ig, "") : data; break;
case 6 : return column === 6 ? data.replace(/<.*?>/ig, "") : data; break;
default : return data; break;
}
}
}
}
};
来源:https://stackoverflow.com/questions/35986288/trying-to-strip-html-from-datatables-during-export