Copy to clipboard with break line

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 you gonna get:

Name: testSurname: testEmail: [email protected]: testCity: testCountry: nullAd Category: testPlan: nullWebsite: Company name: test??????: test

What I want:

I want, if possible, to copy text in a newline. The same as it is when you copy it:

Name: test
Surname: test
Email: [email protected]
...

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}

$( "#FailCopy" ).click(function() {
  alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!--text that i want to copy-->
    <h2>Div #error-details: the text I want to copy to clipboard:</h2>
    <er id="error-details">Name: test<br>Surname: test<br>Email: [email protected]<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>??????: test</er>

    <br><br>
    
    <button id="FailCopy" type="button"  
     onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>

I have also tried to replace <br> with \n and \r\n by adding the following css rule to my div: white-space:pre-wrap; without any signs of success.

Answers:

Answer

You have a few problems with the code.

First problem in your code is the $(element).text()jquery text() strips your code from html including the <br> tags. So there is no newlines in the clipboard text since all html newlines are stripped away.. so nothing to replace.

If you want to keep <br> as newlines you need to use .html() and parse your text more manually.

Second problem is that you use <input> tag. <input> tag is only single lines so u cant have any newline in there. you need to use <textarea> for the conversion.

The last problem is as above that you also should use \r\n for windows users.

I updated your snippet with a working version.

function copyToClipboard(element) {
  var $temp = $("<textarea>");
  var brRegex = /<br\s*[\/]?>/gi;
  $("body").append($temp);
  $temp.val($(element).html().replace(brRegex, "\r\n")).select();
  document.execCommand("copy");
  $temp.remove();
}

$( "#FailCopy" ).click(function() {
  alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!--text that i want to copy-->
    <h2>Div #error-details: the text I want to copy to clipboard:</h2>
    <er id="error-details">Name: test<br>Surname: test<br>Email: [email protected]<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>??????: test</er>

    <br><br>
    
    <button id="FailCopy" type="button"  
     onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>

Answer

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(textarea);

    // 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);
    }
Answer

Two things are wrong:

(1) According to the jquery documentation for text:

The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)

And their example,

<div class="demo-container">
    <div class="demo-box">Demonstration Box</div>
    <ul>
        <li>list item 1</li>
        <li>list <strong>item</strong> 2</li>
    </ul>
</div>

The code $( "div.demo-container" ).text() will produce:

Demonstration Box list item 1 list item 2

So just use the html() method instead to fetch the innerHTML.


(2) The <input> tag removes newlines. Use textarea instead. See: this answer for more info.


Hopefully this spinet will work.

function copyToClipboard(element) {
  var $temp = $("<textarea>");
  $("body").append($temp);
  var html = $(element).html();
  html = html.replace(/<br>/g, "\n"); // or \r\n
  console.log(html);
  $temp.val(html).select();
  document.execCommand("copy");
  $temp.remove();
}

$( "#FailCopy" ).click(function() {
  alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!--text that i want to copy-->
<h2>Div #error-details: the text I want to copy to clipboard:</h2>
<er id="error-details">Name: test<br>Surname: test<br>Email: [email protected]<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>??????: test</er>

<br><br>
    
<button id="FailCopy" type="button"  
     onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>

Answer

Your code is probably working well, but Notepad can't handle Unix' \n newlines, it only can handle \r\n and this is why you don't see them.

Please download a more advanced editor (like Notepad++, https://notepad-plus-plus.org) and try pasting it there. And not only that, but it has a lot of other very cool features like syntax highlighting, macros and plugins so it's worth using it for more purposes than that.

If you want to make the newlines work in MS apps, you need to replace the newlines just before you copy by using this line:

$temp = $temp.replace(/\n/g, "\r\n");

For printing in HTML you would need to replace \n with
, like this:

$temp = $temp.replace(/\n/g, "<br>");

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.