Guide on duplicating text and line breaks in JavaScript

There is some text that looks like this

text = 'line 1' + "\r\n";
text+= 'line 2' + "\r\n";
text+= 'line 3' + "\r\n";

I have developed a function to help facilitate copying it to the clipboard

function copyToClipboard(text)
{

    var copyElement = document.createElement("span");
    copyElement.appendChild(document.createTextNode(text));
    copyElement.id = 'tempCopyToClipboard';
    angular.element(document.body.append(copyElement));

    // select the text
    var range = document.createRange();
    range.selectNode(copyElement);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);

    // copy & cleanup
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    copyElement.remove();
}

Is there a way to copy this text to the clipboard without losing the newline characters?

Answer №1

Apologies everyone, my mistake. After taking a closer look, I now see that I should have utilized a textarea instead of a span in this snippet.

Answer №2

It appears that the function is functioning properly for me when I specify the text within it. Have you verified that the new lines are being passed into the function as expected?

function copyToClipboard()
{
    var text = 'line 1' + "\r\n";
    text+= 'line 2' + "\r\n";
    text+= 'line 3' + "\r\n";
    
    var copyElement = document.createElement("span");
    copyElement.appendChild(document.createTextNode(text));
    copyElement.id = 'tempCopyToClipboard';
    angular.element(document.body.append(copyElement));

    // select the text
    var range = document.createRange();
    range.selectNode(copyElement);
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);

    // copy & cleanup
    document.execCommand('copy');
    window.getSelection().removeAllRanges();
    copyElement.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<button type="button" onclick="copyToClipboard()">Copy text to clipboard</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Passing the response from an AJAX request to JavaScript

When I call ajax to retrieve a value from an asp page and return it to the calling javascript, the code looks like this: function fetchNameFromSession() { xmlhttp = GetXmlHttpObject(); if (xmlhttp == null) { alert("Your browser does n ...

You can click on the link within the Leaflet Popup to trigger JavaScript functionality

My leaflet map is functioning with GeoJSON polygons and popups attached to each one. These popups display information about the polygon. I want a link inside the popup that, when clicked, triggers a JavaScript function to retrieve and display smaller polyg ...

Migration processes encountering delays due to running nodes

When running migrations in Node, I am encountering a timeout error. The specific error message is: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. Here is the ...

$scope variables, ng-hide/show directive

There seems to be a confusion with $scope in my code. I have ng-hide/shows that use a variable in the top nav, controlled by "NavController". Inside an ng-view, controllers are linked via the app config function. The appointment setting functionality is ha ...

Looking for assistance with iterating through various layers of nested arrays on a map

Feeling completely stumped after exhausting all my options, I've finally reached out for help. I just can't figure it out... My blog posts are structured like this: const posts = [ { section: 'one', title: [ 'third', &apo ...

Getting a select2 value in AngularJs can be accomplished by using the ng-model

Why am I unable to retrieve the select2 value? Here's my current code snippet: <select id="categoryId" class="category" ng-model="selectedCategory" ng-options="selectedCategories.name for ...

I am facing an issue where this loop is terminating after finding just one match. How can I modify it to return

I am currently working with an array that compares two arrays and identifies matches. The issue is that it only identifies one match before completing the process. I would like it to identify all matches instead. Can anyone explain why this is happening? ...

Utilizing the keyword 'this' within a function of a JavaScript class that is invoked with the .map method

I am working with the RegisterUser class which contains various methods and properties: class RegisterUser { constructor(username, password, ispublic){ this.username = username; this.password = password; this.ispublic = ispublic; this.id ...

Exploring the world of design with React JS and MUI's diverse styling options

Exploring the various styling options offered by MUI From useTheme, styled, makeStyles to other methods - what sets them apart and how do they differ in use cases? We're looking for a comprehensive breakdown of their unique features, practical appli ...

Automatically redirect users on page refresh using jQuery

I am attempting to use jQuery to detect when the user refreshes the page in order to redirect, but I can't seem to get it working. Can someone help me figure out what is wrong with this code? <?php include 'instagram.php'; ?> <! ...

Issues with IE 11: SVG Map Not Triggering Mouseenter or Mouseleave Events

I've been grappling with this issue for the past couple of days and despite trying numerous solutions, nothing seems to be working. My SVG map of the US has jQuery mouseenter and mouseleave events that function properly in browsers other than IE 11 ( ...

As two divs glide across the screen, the top div remains hidden from view

To enhance our user experience, we are tasked with creating a captivating screen saver featuring 3 images. The bottom image will remain fixed in its position. The middle image should move across the screen. Lastly, the top image will move at a faster ...

Trouble with highlighting the chosen menu item

I have been attempting to implement this code snippet from JSFiddle onto my website. Although I directly copied the HTML, used the CSS inline, and placed the Javascript in an external file, the functionality does not seem to be working properly. Feel free ...

Encountering an issue when making a POST request using JSON data

I've encountered an issue with my server.js file code. I'm trying to push JSON content into the user object, but I keep getting an error message. Can someone please help me identify where I've gone wrong? const express = require('expre ...

What is the procedure for iterating through the square brackets of a JSON array?

Here's the data I have: $json_data_array = '[ { "id": 1, "value": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd7cdffcbdacccb91dcd0d2">[email protected]</a>", ...

Instructions for displaying a React component in the <main> element when employing react-burger-menu

Check out my code here. Utilizing react-burger-menu has allowed me to successfully implement the sidebar feature. The sidebar functionality is working as expected. My current challenge involves figuring out how to open the content for Home or GG within ...

Issue with Material UI components: The Select component is collapsed and the autoWidth functionality is not

The Material UI (React) Select component is not expanding in width as expected, even with the autoWidth property. https://i.sstatic.net/h3H0V.png <FormControl margin="dense"> <InputLabel id="prefix-label">Prefi ...

What is the best approach to streamline and optimize this JavaScript logic code for greater efficiency?

Working on a project, I find myself dealing with 21 buttons that can be in either an active or inactive state. The state of certain buttons is influenced by the press of other buttons as well as their own activation. To handle this in my HTML, I utilize ng ...

Using jQuery to toggle the visibility of HTML elements

Hi there, I am trying to create an interactive HTML sidebar where each section shows its respective posts when clicked. However, I am facing issues as the content keeps hiding continuously. <div class="col-md-3"> <div class="list-grou ...

Why won't the div move when I click it?

Could you please explain why my JavaScript code isn't functioning as expected? The intended behavior is for the 'mark' div to move to the current mouse coordinates upon clicking within the map. ...