I want to copy a text to clipboard but in a new line.
Problem:
If you click the button in the snippet and paste in the notepad this is what
Non-jQuery Solution to simply copy a string with line breaks to clipboard
Please refer to code comments for clarity.
function copyStringWithNewLineToClipBoard(stringWithNewLines){
// Step 1: create a textarea element.
// It is capable of holding linebreaks (newlines) unlike "input" element
const myFluffyTextarea = document.createElement('textarea');
// Step 2: Store your string in innerHTML of myFluffyTextarea element
myFluffyTextarea.innerHTML = stringWithNewLines;
// Step3: find an id element within the body to append your myFluffyTextarea there temporarily
const parentElement = document.getElementById('any-id-within-any-body-element');
parentElement.appendChild(myFluffyTextarea);
// Step 4: Simulate selection of your text from myFluffyTextarea programmatically
myFluffyTextarea.select();
// Step 5: simulate copy command (ctrl+c)
// now your string with newlines should be copied to your clipboard
document.execCommand('copy');
// Step 6: Now you can get rid of your fluffy textarea element
parentElement.removeChild(myFluffyTextarea);
}