[Vuejs]-Vue js โ€“ parsing data from clipbord (excel)

0๐Ÿ‘

โœ…

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}
},

0๐Ÿ‘

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.

Leave a comment