How can I prevent javascript from copying a line break to clipboard?

Viewed 441

I found a program that allows me to copy data from a div to the clipboard. When copied, it adds a line break even though there's no line break in my div. How can I remove any line breaks from the copy.

  function copyDivToClipboard(elem) {
    var range = document.createRange();
    range.selectNode(document.getElementById(elem));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
    
}
<div id='test'>This is a test</div>

<button onclick='copyDivToClipboard("test")'>Copy to clipboard</button>

2 Answers

Instead of range.selectNode use range.selectNodeContents

function copyDivToClipboard(elem) {
    var range = document.createRange();
    range.selectNodeContents(document.getElementById(elem));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
}
<div id="test">
  This is a test
</div>

<button onclick='copyDivToClipboard("test")'>Copy to clipboard</button>

The div element you are copying contains the newline as part of its text content when Javascript is copying it. If you instead use a span you will not get the newline with the text.

https://jsfiddle.net/sLv9ux50/

Related