Search code examples
angulartypescriptclipboard

Angular get data from clipboard


im using bellow function to get copied data from clipboard

onPasteData(section:string){
navigator.clipboard.readText().then(s => 
  input = s
); 
}

s holding bellow data line by line with line break before the last line

Tony
USA

addtionline3

onPastData in a click function. what im try to do is move this data into array

expected array

let finalArray = [{ "Name" : Tony,
                     "Country" : USA,
                    "Additional" : addtionline3
                   }]

i tried using split but enable to get the result

const lines = input.split(/\r?\n/).filter(line => line.trim() !== '');

Solution

  • We can use shift array method to pop the first element from the array, and then push the remaining lines to Additional.

    const input = `Tony
    input
    
    addtionline3`;
    
    const lines = input.split(/\r?\n/).filter(line => line.trim() !== '');
    
    const output = lines.length >= 2 ? [{
      Name: lines.shift(),
      Country: lines.shift(),
      Additional: lines,
    }] : [];
    
    console.log(output);