Copy HTML content with Javascript, paste as formatted text

Viewed 621

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 Answers

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");
};

function conVert(event) {
  event.preventDefault();
  let val = answer.value
  console.log(val)
  result.insertAdjacentHTML('afterbegin', val);
  // you can use event.target here to past it as formated to targeted element onpaste
}

// on button
buttonpaste.onclick = function(event) {
  conVert(event)
}
//on paste
document.onpaste = function(event) {
  console.log("Paste")
  conVert(event)
};
#result {
  min-height: 100px;
  background-color: yellow
}

#result2 {
  min-height: 100px;
  background-color: gray;
}
<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>
<div id="result2" contentEditable="true"></div>

Related