简体   繁体   中英

Remove invisible carriage return from CSV using javascript

I try to parse a CSV in Google Apps Script (Google Sheets), with the code below:

var file = DriveApp.getFileById('xx');
var blobasstr = file.getBlob().getDataAsString();
var csvData = Utilities.parseCsv(blobasstr);

All works fine except from the fact that there are invisible carriage returns in my CSV within cells, which result in extra rows being created in the middle of cells. These carriage returns are a result from the fact that the source data contains cells with two address lines (and the carriage return in the middle). When I open the CSV in notepad I have to type my cursor twice to get past this point which strengthens my idea that there is a hidden carriage return there.

Can I use a regex on my blobasstr that removes these invisible carriage returns, but of course keeps the usual carriage returns at the end of each line?


Edit: Thanks for referring to the earlier question. With the regex:

blobasstr.replace(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]\r\n(?:\\[\s\S][^'\\]\r\n)*')/g, '\\r\\n');

I am indeed able to remove the 'hidden' returns which is a great start. The thing is that I now end up with the text \\r\\n in the cells that had a invisible return (instead of the original content of the cell, this is probably caused by the replacement argument '\\r\\n' Is there an alternative for this that keeps the original content of the cell (of course without the hidden carriage return?) Thanks a lot!


The help is really appreciated!

Chris

notepad expects dos line endings \\r\\n and doesn't handle unix line endings single \\n , i could reproduce behavior with a simple file with \\n , the cursor must be typed twice to advance.

Seems Utilities.parseCsv can't handle multiline cells, because can't specify an optional enclosing character like " .

这最终为我做了什么:

var blobasstr = blobasstr2.replace(/(?=["'])(?:"[^"\]*(?:\[\s\S][^"\]*)*"|'[^'\]\r\n(?:\[\s\S][^'\]\r\n)*')/g, function(match) { return match.replace(/\n/g,"")} );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM