I have written this function to copy text to clipboard. It copies content but it add line feeds to the string copied.
function copyToClipboard(text) {
// console.log("text",text);
const textarea = document.createElement('textarea');
textarea.textContent = text;
document.body.appendChild(textarea);
var selection = document.getSelection();
var range = document.createRange();
range.selectNode(textarea);
selection.removeAllRanges();
selection.addRange(range);
const success = document.execCommand('copy');
selection.removeAllRanges();
document.body.removeChild(textarea);
return success;
console.log("now paste in the text area");
}
$('button').click(function () {
copyToClipboard($('#ip').val());
})
textarea{
width:100%;
height: 200px;
border: 1px solid grey;
}
input{
min-width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='ip' placeholder="insert some text and press copy"><button>Copy</button>
<textarea placeholder='perform paste in this textarea and you will see line feeds'>
</textarea>
If you run the snippet and follow instructions, you can see the line break in the text area.
What I have tried.
I have used below code to copy to clipboard, But due to some reason it is not working in my project. But it worked in other code bases, even in browser console. And it doesn't contain the line feeds.
function copyToClipBoard2(text) {
var textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
var successful = document.execCommand('copy');
if (successful){
console.log("copied to clipboard");
}
document.body.removeChild(textArea);}
How can I make it not to add line feeds to the copied text ?
from document.execCommand('copy') command add line feeds in the start and end of the string
No comments:
Post a Comment