I'm trying to parse data that the user paste from an excel file. y code look like this :
onPastingContacts(e) {
const pastedData = e.clipboardData.getData('Text');
const allPastedFields = pastedData.split('\n').filter(el => el !== '');
allPastedFields.forEach(el => {
const field = el.split('\t');
let element = {
'field1': field[0]?.replace(/\r/g, ''),
'field2': field[1]?.replace(/\r/g, ''),
'field3': field[2]?.replace(/\r/g, ''),
'field4': field[3]?.replace(/\r/g, ''),
'field5': field[4]?.replace(/\r/g, ''),
'field6': field[5]?.replace(/\r/g, '')
};
Object.keys(element).forEach((key) => (element[key] == null) && delete element[key]); // remove empty fields from object
Data.push(element)
});
return {Data}
},
And it works well in general, The problem is if the file contains text with '\n' or '\t' it parses it as if it were a new line in the file (or if it \t a new cell).
for example, if I'm trying to paste this file :
if I print the pasted data its look like this :
523961234 "This is an example with new line "
and if I print the Data array its look like this :
[{field1: '523961234', field2: 'This is an example'},
{field1: 'with new line '}]
And I need that this will be the result:
[{field1: '523961234', field2: 'This is an example \n with new line '}]
I know why it's append , does anyone have an idea how I can parse in a way that its work?
CodePudding user response:
What you can do is remove the new lines everywhere where in-between quotation marks. You can use this RegEx /\n (?=(?:(?!\"|\").)*\")/gs
to find these new lines.
So line
onPastingContacts(e) {
const pastedData = e.clipboardData.getData('Text');
const regEx = /\n (?=(?:(?!\"|\").)*\")/gs;
const allPastedFields = pastedData.replaceAll(regEx, " ").split('\n').filter(el => el !== '');
// Rest of your code here.
}
Note: If you need to preserve the newLines in each field you can replace the newLines with a placeholder - Example .replaceAll(regEx,'{NEW_LINE}')
. Then when you parse the field you can replace it with a new line - Example .replaceAll('{NEW_LINE}', '\n')
.
Original RegEx inspiration here.
CodePudding user response:
I split by '\r\n'. and this work for me. the new lines inside the cell were just \n . this is my code :
onPastingContacts(e) {
const pastedData = e.clipboardData.getData('Text');
const allPastedFields = pastedData.split('\r\n').filter(el => el !== '');
allPastedFields.forEach(el => {
const field = el.split('\t');
let element = {
'field1': field[0]?.replace(/\r/g, ''),
'field2': field[1]?.replace(/\r/g, ''),
'field3': field[2]?.replace(/\r/g, ''),
'field4': field[3]?.replace(/\r/g, ''),
'field5': field[4]?.replace(/\r/g, ''),
'field6': field[5]?.replace(/\r/g, '')
};
Object.keys(element).forEach((key) => (element[key] == null) && delete element[key]); // remove empty fields from object
Data.push(element)
});
return {Data}
},