skip to Main Content

my js string looks like this ‘coolstring’
i want to output this string in html like this ‘cool string’
when i copy this string in the browser and paste it, in a word document for example, the whitespace should not copied -> coolstring

i tried different approaches according to this site: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace

2

Answers


  1. The space can be in a pseudo element so will show but as it isn’t in the DOM it will not be copied:

    <style>
      .coolstring>span::after {
        content: ' ';
      }
      
      .coolstring>span:last-child::after {
        content: '';
      }
    </style>
    <div class="coolstring"><span>cool</span><span>string</span></div>
    Login or Signup to reply.
  2. You can replace the default copyText event for a specific element. More info about copyText here

    document.getElementById('copyText').addEventListener('copy', function(event) {
          event.preventDefault();
    
          const selectedText = window.getSelection().toString();
    
          // Remove spaces
          const modifiedText = selectedText.replace(/s/g, '');
    
          // Create a temporary textarea to copy the modified text to the clipboard
          const textarea = document.createElement('textarea');
          textarea.value = modifiedText;
          document.body.appendChild(textarea);
          textarea.select();
          document.execCommand('copy');
          document.body.removeChild(textarea);
        });
    

    Here’s the code working in a codepen demo
    the demo only shows it on a div element, but it works on paragraphs and headers aswell

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search