复制到剪贴板时换行

32

我想将文本复制到剪贴板中,但是在新行中。

问题:

如果您单击代码片段中的按钮并粘贴到记事本中,您将获得以下内容:

Name: testSurname: testEmail: test@gmail.comAddress: testCity: testCountry: nullAd Category: testPlan: nullWebsite: Company name: testΜήνυμα: test

我想要的:

如果可能,我希望在新行中复制文本。与复制时一样:

Name: test
Surname: test
Email: test@gmail.com
...

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: test@gmail.com<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>

我也尝试使用以下CSS规则,将<br>替换为\n\r\n,并添加到我的div中:white-space:pre-wrap;但是没有看到任何成功的迹象。


可能是将多行文本复制到剪贴板的重复问题。 - Ananthakrishnan Baji
4个回答

47
你的代码存在几个问题。
首先是你的代码中使用了 $(element).text()jquery text() 方法,它会去除包括 <br> 标签在内的 html 代码。因此,剪贴板文本中没有换行符,因为所有的 html 换行符都被去除了,所以没有东西可以替换。
如果你想将 <br> 保留为换行符,你需要使用 .html() 方法,并手动解析你的文本。
第二个问题是你使用了 <input> 标签。 <input> 标签只能单行输入,所以你不能在其中插入任何换行符。你需要使用 <textarea> 进行转换。
最后一个问题就像上面所说,你还应该为 Windows 用户使用 \r\n
我已经更新了你的代码片段,现在可以正常工作了。

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: test@gmail.com<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>


16

无需使用jQuery的解决方案,可将带有换行符的字符串简单地复制到剪贴板

请参考代码注释以获得更清晰的说明。

    function copyStringWithNewLineToClipBoard(stringWithNewLines){

        // Step 1: create a textarea element.
        // It is capable of holding linebreaks (newlines) unlike "input" element
        const mySmartTextarea = document.createElement('textarea');
        
        // Step 2: Store your string in innerHTML of mySmartTextarea element        
        mySmartTextarea.innerHTML = stringWithNewLines;
        
        // Step3: find an id element within the body to append your mySmartTextarea there temporarily
        const parentElement = document.getElementById('any-id-within-any-body-element');
        parentElement.appendChild(mySmartTextarea);
        
        // Step 4: Simulate selection of your text from mySmartTextarea programmatically 
        mySmartTextarea.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 "smart" textarea element
        parentElement.removeChild(mySmartTextarea);
        }

现在,只需复制并粘贴这个简短的方法,并加上你自己的注释,以便未来的开发人员管理你的代码。 或者只需引用回答即可。

function copyStringWithNewLineToClipBoard(stringWithNewLines){
    const mySmartTextarea = document.createElement('textarea');
    mySmartTextarea.innerHTML = stringWithNewLines;
    const parentElement = document.body.appendChild(mySmartTextarea);
    mySmartTextarea.select();
    document.execCommand('copy');
    parentElement.removeChild(mySmartTextarea);
    }

1
当修复这个小bug时,parentElement.appendChild(textarea)工作得很好;=> parentElement.appendChild(myFluffyTextarea); - John T
1
感谢您发现那个难缠的小错误,我会立即解决它。 :) - KeshavDulal
所有的parentelement部分对我来说都很丑陋,为什么不直接使用document.body.appendChild(mySmartTextarea)呢? - John
是的,那也完全可行。我不知道为什么三年前我没有意识到这一点。 - KeshavDulal
parentElement.removeChild(mySmartTextarea);在我的情况下出现了错误,所以我将其移除了。其他部分都正常工作。 - Ujjwal Raijada

4

有两个问题:

(1) 根据jQuery的text文档:

.text()方法的结果是包含所有匹配元素的组合文本的字符串。(由于不同浏览器中HTML解析器的差异,返回的文本可能会因换行和其他空格而有所不同。)

他们的例子:

<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>

代码$( "div.demo-container" ).text()将产生:

演示框列表项1列表项2

所以,只需使用html()方法来获取innerHTML


(2)<input>标签会删除换行符。请改用textarea。更多信息请参见:此答案


希望这个片段能够正常工作。

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: test@gmail.com<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>


2
你的代码可能运行良好,但是Notepad无法处理Unix的 \n 换行符,它只能处理 \r\n,这就是为什么你看不到它们的原因。
请下载一个更高级的编辑器(如Notepad++,https://notepad-plus-plus.org),并尝试将其粘贴到那里。而且,它还有许多其他非常酷的功能,如语法突出显示、宏和插件,因此值得用于更多目的。
如果你想在MS应用程序中使换行符起作用,需要在复制之前使用以下行替换换行符:
$temp = $temp.replace(/\n/g, "\r\n");

在HTML中进行打印时,您需要将换行符 \n 替换为
,操作方式如下:

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

实际上,我想在Microsoft Outlook (Windows 10应用程序)中进行复制。同样的事情没有换行符。 - user7038047
这是我如何使用javascript打印文本的方式:$("#error-details").html(Name: '+onoma+"<br>")+,我应该把 \r\n 放在哪里? - user7038047
我在函数中添加了这行代码,但是出现了错误 "message": "Uncaught TypeError: $temp.replace is not a function"。如果这对你有用,可以将我的代码片段复制到你的答案中并提供解决方案。 - user7038047
我在控制台中尝试了以下内容,并且它起作用了: var $temp = "abcd\nabcd"; $temp = $temp.replace(/\n/g, "\r\n"); console.log($temp); // ==> abcd\r\nabcd - techfly
你的回答只解决了问题的一小部分。 - JohanSellberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接