Copy Button Preserving Line Breaks

前端 未结 2 1265
暖寄归人
暖寄归人 2020-12-01 14:49

I have some very basic Javascript that copies text upon the push of a button. My problem is that it doesnt preserve line breaks:



        
2条回答
  •  [愿得一人]
    2020-12-01 15:21

    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 and
      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 
    and 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 = $("