Search code examples
javascripthtmlcopycopy-pastepaste

How can I get my Copy and Paste function to keep new line formatting?


I only need this to work on Google Chrome so there is no requirement for multi-browser compatible code.

This is the JS function I use to copy the text to clipboard.

 // Copy text to clip-board JS
  
  function copy(txt){
    var cb = document.getElementById("cb");
    cb.value = txt;
    cb.style.display='block';
    cb.select();
    document.execCommand('copy');
    cb.style.display='none';
  }

 var var1='download here: \n www.link-to-download.com';

Here is my HTML

  <button class="buttonClass" onclick="copy(softwareinstall)">Install software</button>
    <textarea id="cb" style="display: none"></textarea>

When I click the button, it will copy to clipboard, however when I paste the content into somewhere else for example notepad and outlook, the text is all on one line and the \n does nothing.

I would like for the string to be split onto 2 seperate lines.

Thank you in advanced.


Solution

  • If it is an option, you could easily preserve you text content by using navigator.clipboard.writeText() instead of document.execCommand() as that does not copy from the DOM. Something like:

    const str = "Text \n on \n different lines";
    navigator.clipboard.writeText(str).then(() =>
       console.log("copied")
    );