Copy Button Preserving Line Breaks
Solution 1:
First off, the <input>
element doesn't preserve line breaks. You can use the <textarea>
element instead. Since your HTML may contain <br>
elements instead of line break characters, I would also suggest using jQuery to prepend \r\n
before each <br>
.
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()
}
<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>
Solution 2:
We have adapted the copyToClipboard function to get it to work with our application. The changes were the following:
- change the input to textarea so that the line breaks are passed;
- change the text() function to html() so that the HTML is passed;
- use a regex to replace each HTML br with the linefeed;
- use another regex to strip the remaining HTML. The HTML in our
application should only have
<b>
and<br>
tags, so the simple regex should work, and also handle the odd tag that might be present.
Here is our adapted function, along with comments:
// 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();
}
Btw, if somebody knows why the regex from the cited page had the (>|$) that we changed to >, we would appreciate gaining the understanding as to why the dollar sign that we removed is needed.