javascriptjquerycsvexport-to-csvjquery-csv

How to add new line in CSV generated by jQuery?


I have a list that needs to be generated as a CSV. Here it is:

[101, true, P, b, br, 2020], [101, true, P, 20, br, 2020], [101, true, P, b, breach, 2020]

And I wrote this to convert it:

var link = document.createElement('a');
link.id = 'download-csv';
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(queries.toString().replaceAll("[","").replaceAll("],","\\r\\n").replaceAll(",",";").trim().replaceAll("]","")));
link.setAttribute('download', 'yourfiletextgoeshere.csv');
document.body.appendChild(link);
document.querySelector('#download-csv').click();

And generated a CSV file is like this:

101; true; P; b; br; 2020\r\n101; true; P; 20; br; 2020\r\n101; true; P; b; br; 2020

Instead of breaking the line, it continues as if \r\n is a string.


Solution

  • From the comment by user freedomn-m, which OP responded 'solved' their problem:

    Use this:

    .replaceAll("],","\\r\\n") -> .replaceAll("],","\r\n")