0

A textarea element contains text with html tags.

Example:

<textarea>This is a <b>sample</b>.</textarea>

How do I copy its text to the clipboard as html? So when I paste it in e.g. MS Word, sample appears bold?

isherwood
  • 58,414
  • 16
  • 114
  • 157
smolo
  • 737
  • 1
  • 15
  • 27
  • 1
    HTML is just text. It's up to the software that you paste the text into to decide what to do with it. – Pointy Apr 07 '22 at 15:25
  • @tevemadar this answers my question. Thanks! – smolo Apr 07 '22 at 15:31
  • Also this: [Paste HTML into Word](https://superuser.com/questions/426139/paste-html-into-word) – isherwood Apr 07 '22 at 15:31
  • @Pointy: Copy text from the wysiwig (left) and the textarea (right) from https://html-online.com/editor and the result in MS Word is not the same. – smolo Apr 07 '22 at 15:34

1 Answers1

0

This works for me:

function copyToClip(str) {

  function listener(e) {
    e.clipboardData.setData("text/html", str);
    e.clipboardData.setData("text/plain", str);
    e.preventDefault();
  }
  
  str = str.replace(/(?:\r\n|\r|\n)/g, '<br>');

  document.addEventListener("copy", listener);
  document.execCommand("copy");
  document.removeEventListener("copy", listener);
  
};

copyToClip(mytextarea.value);
smolo
  • 737
  • 1
  • 15
  • 27
  • @isherwood My answer is no duplicate and still my question is flagged as duplicate... Anyway, I've found an answer. – smolo Apr 07 '22 at 15:54