How to completely remove spaces in copied text in Javascript

How to completely remove spaces in copied text in Javascript

Problem Description:

I put a javascript copy button, but this button takes all the spaces in the html. How can I solve this?

JavaScript File:

$(document).ready(function() {
  $('button').click(function(){
    var btntxt = $(this).text();
    
     var copy = $(this).parent().find('.copy').text();

     
     var $temp = $("<input>");
     $("body").append($temp);
     $temp.val(copy).select();
     document.execCommand("copy");
     $temp.remove();
     
    
    
    $('.confirmation').hide().html('<b>' + btntxt + ' </b> Kopyalandı! ').fadeIn(100).delay(1200).fadeOut(200);
   
    $( '.main' ).trigger( "click" );
  });
  
  $('.main div').click(function(){
      var range = document.createRange();
      var selection = window.getSelection();
      range.selectNodeContents(this);
      selection.removeAllRanges();
      selection.addRange(range);
  });
});

Html File:

<div class="bank-account mb-4 mt-4">
            <button class="button1">
                <span class="copy">
                    <span class="name-text">Text will come here</span>
                </span>
                <button class="button2">
                    <text class="bank-name">Also Text will come here too</text>
                    <i class="far fa-copy" aria-hidden="true"></i>
                </button>
            </button>
</div>

Also i tried to add remove spaces code but it didn’t work.

Solution – 1

replace this line
var copy = $(this).parent().find('.copy').text();
with this one
var copy = $(this).parent().find('.copy').text().replaceAll(" ", "");

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject