复制按钮保留换行符

时间:2017-03-15 17:07:50

标签: javascript

我有一些非常基本的Javascript,只需按一下按钮即可复制文本。我的问题是它不会保留换行符:

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

我真的希望能够添加到上面的脚本中,以避免在网站上进行大量更改。

我在其他帖子上看过的内容如:

post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');

理论上它可以工作(我认为),但我吮吸Javascript。

有什么建议吗?

由于

2 个答案:

答案 0 :(得分:13)

首先,<input>元素不会保留换行符。您可以改用<textarea>元素。由于您的HTML可能包含<br>个元素而不是换行符,因此我还建议您使用jQuery在每个\r\n之前添加<br>

&#13;
&#13;
function copyToClipboard(element) {
  var text = $(element).clone().find('br').prepend('\r\n').end().text()
  element = $('<textarea>').appendTo('body').val(text).select()
  document.execCommand('copy')
  element.remove()
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p contenteditable="true">Type to edit <br> this text</p>
<button onclick="copyToClipboard('p')">Copy to Clipboard</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我们已经调整了copyToClipboard函数以使其与我们的应用程序一起使用。变化如下:

  • 将输入更改为textarea,以便传递换行符;
  • 将text()函数更改为html(),以便传递HTML;
  • 使用正则表达式将每个HTML br替换为换行符;
  • 使用另一个正则表达式来删除剩余的HTML。我们的HTML 应用程序应该只有<b><br>标记,因此简单的正则表达式应该可以工作,并且还可以处理可能存在的奇数标记。

这是我们改编的功能,以及评论:

// Note: original replace used to strip HTML tags from https://stackoverflow.com/questions/5002111/javascript-how-to-strip-html-tags-from-string ReactiveRaven.
// However, replaced closing (>|$) with > as I don't understand why the check for $ is there, as it implies that $ is part of an HTML tag.
// Our requirement highly constrains the HTML, to mainly have <br> and <b> tags, so the general objection to parsing HTML with regex
// as at https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags community wiki is not applicable.
// BTW, that page is very entertaining!
function copyToClipboard(element)
{
    var $temp = $("<textarea>");
    $("body").append($temp);
    var x = $(element).html().trim().replace(/<br>/g, '\n').replace(/<\/?[^>]+>/g, '');
    $temp.val(x).select();
    document.execCommand("copy");
    $temp.remove();
}

顺便说一句,如果有人知道为什么引用页面中的正则表达式具有我们更改为&gt;的(&gt; | $),我们希望获得理解为什么我们删除的美元符号是必需的。

相关问题