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() !== '');
0
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);
Here’s a solution that should work:
function onPasteData(section: string) {
navigator.clipboard.readText().then(input => {
// Split the input by line breaks and remove empty lines
const lines = input.split(/r?n/).filter(line => line.trim() !== '');
// Create the object with the parsed data
const parsedData = {
Name: lines[0] || '',
Country: lines[1] || '',
Additional: lines[2] || ''
};
// Create the final array with the parsed object
const finalArray = [parsedData];
console.log(finalArray);
// You can now use finalArray as needed
});
}
This code does the following:
- We use
navigator.clipboard.readText()
to get the clipboard content. - We split the input string by line breaks and remove any empty lines using
split(/r?n/)
andfilter()
. - We create an object
parsedData
with the desired structure, assigning values from thelines
array to the corresponding keys. - We create
finalArray
by wrappingparsedData
in an array.
The resulting finalArray
will have the structure you’re looking for:
let finalArray = [{
"Name": "Tony",
"Country": "USA",
"Additional": "addtionline3"
}]
This approach is more robust as it handles cases where some lines might be missing. If a line is missing, the corresponding value in the object will be an empty string.