Copy HTML content with Javascript, paste as formatted text

I have a field where a user can input raw HTML. This looks like:

<input type="text" id="editor" value="<p>Hi,</p><p>Here is a <a href='domain.com'>link</a> I'd like you to visit.</p>" />

Now, I need a "copy to clipboard" button that takes the content of this field in such a way that we can paste it as formatted text (without the HTML markup). In the example above, the copy/paste output should be:

Hi,

Here is a [link][1] I'd like you to visit.

I’ve implemented the "copy to clipboard" button like this:

let answer = document.getElementById("editor");
answer.select();
document.execCommand("copy");

This places the content of the input on the clipboard, however when I paste it elsewhere I get the raw HTML.

I need some way to convert HTML into formatted text, but the only solution I found is this and it doesn’t work for links:

enter link description here

Is there a native Javascript way to do this? If not, what is the best solution?

1 thought on “Copy HTML content with Javascript, paste as formatted text”

  1. Try with Element.insertAdjacentHTML()

    let answer = document.getElementById("editor");
    let result = document.getElementById("result");
    let button = document.getElementById("button");
    
    button.onclick = function() {
      answer.select();
      document.execCommand("copy");
    };
    
    buttonpaste.onclick = function() {
      let val = answer.value
      console.log(val)
      setTimeout(function() {
        result.innerHTML = ""
        result.insertAdjacentHTML('afterbegin', val);
      }, 100);
    }
    #result {
      min-height: 100px;
      background-color: yellow
    }
    <input type="text" id="editor" value="<p>Hi,</p><p>Here is a <a href='domain.com'>link</a> I'd like you to visit.</p>" />
    
    <button id="button">COPY</button>
    <button id="buttonpaste">PASTE</button>
    
    
    <div id="result" contentEditable="true"></div>
    Reply

Leave a Comment