JSFiddle - React, Tailwind, and code Playground

HTML

<textarea id="textarea" rows='20" cols="50">
</textarea>
<input type="button" value="Substitute selected text" onclick="setTextareaSelection()"/>

JavaScript

function  setTextareaSelection(newText) {
     var selText;
     newText="This is a text \n to insert" ;
  var textarea=document.getElementById('textarea'); 
   if (window.getSelection) {
    var selText = "";
    selText = textarea.value.slice(textarea.selectionStart,   textarea.selectionEnd);
    var selEnd =textarea.selectionEnd;
           
    var selTextBefore = textarea.value.substring(0, textarea.selectionStart);
    var selTextAfter = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
 
     if (selText != "") {
        textarea.value = selTextBefore + newText + selTextAfter;
        textarea.setSelectionRange(selEnd,selEnd);
             }
 
         }      
  
     
    }