2017-09-27 2 views
0

divの内容をクリップボードにコピーする以下のJavascriptがあります。Javascriptを使ってトリミングしてクリップボードに送信

divの内容は常に異なりますが、結果には現在、常に結果の前に空白が含まれる約5行の空白行があります。私はこれを変更することはできませんので、結果の前後にあるすべての空白をトリムする関数を以下にします。私は

str.trim()  

はおそらく最高であることを認識してい

は、しかし、JavaScriptの初心者であること、私は以下にそれを挿入するために苦労してきました。

<script> 
function copyToClipboard(element) { 
var $temp = $("<textarea>"); 
var brRegex = /<br\s*[\/]?>/gi; 
$("body").append($temp); 
$temp.val( $(element).html().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '')).select(); 

document.execCommand("copy"); 
$temp.remove(); 
} 

助けることができる誰か?

ありがとうございます!

答えて

1

あなたのコードスニペットは私にとって完璧に機能します。あなたがどこかにトリムを挿入した場合しかし、それはここだろう:

function copyToClipboard(element) { 
    var $temp = $("<textarea>"); 
    var brRegex = /<br\s*[\/]?>/gi; 
    $("body").append($temp); 
    $temp.val($(element).html().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim()).select(); 
    document.execCommand("copy"); 
    $temp.remove(); 
} 

説明は$(要素)の.html()は文字列であり、そしてあなたが後にトリミングする文字列であるということです置き換えたいものを置き換えます。

HTMLのための完全なコードスニペット:

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <title>Copy</title> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
     <script 
      src="https://code.jquery.com/jquery-1.12.4.min.js" 
      integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" 
      crossorigin="anonymous" 
     ></script> 
    </head> 
    <body> 
     <div class="copy" contenteditable="true">HI<br />I am me! <span>I want to kill you!</span></div> 
     <button class="copy-button">copy</button> 
     <script> 

      function copyToClipboard(element) { 
      var $temp = $("<textarea>"); 
      var brRegex = /<br\s*[\/]?>/gi; 
       $("body").append($temp); 
       $temp.val($(element).html().replace(brRegex, "\r\n").replace(/<\/?[a-zA-Z]+\/?>/g, '').trim()).select(); 
       document.execCommand("copy"); 
       $temp.remove(); 
      } 
      $('.copy-button').on('click', _ => { 
       copyToClipboard($('.copy')); 
       console.log("HI"); 
      }); 
     </script> 
    </body> 
</html> 
+0

パーフェクト!それは治療を働いた!ありがとう! – willmadd

関連する問題