srcomptn
srcomptn

Reputation: 81

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.

Upvotes: 2

Views: 6240

Answers (2)

JayCodist
JayCodist

Reputation: 2544

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")
);

Upvotes: 3

timlg07
timlg07

Reputation: 626

This is because the input element doesn't support line breaks, so your \n gets lost. Try to use a textarea instead:

// 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='first line of text \n second line of text';
<button onclick="copy(var1)">Copy Option 1</button>
<textarea id="cb" style="display: none"></textarea>

Upvotes: 2

Related Questions