JSFiddle - React, Tailwind, and code Playground

HTML

<textarea></textarea>
<button>Insert text</button>

CSS

textarea {
  width: 20em;
  height: 30em;
}

JavaScript

$(document).ready(function() {
	$('button').click(function() {
  	var $text = $('textarea');
    
    debugger;
  
		var currentValue = $text.val(),
    		len = currentValue.length,
    		isTextAreaFocused = $text.is(':focus'),
    		optionalNewline = isTextAreaFocused ? '' : '\n';
        
   	var start = $text[0].selectionStart,
    		end = $text[0].selectionEnd,
        beforeText = isTextAreaFocused ? currentValue.substring(0, start) : len,
        afterText = isTextAreaFocused ? currentValue.substring(end) : len;
        
    var insertedText = 'foo',
   			newValue = beforeText + insertedText + afterText + optionalNewline; 
    
    $text.val(newValue);
	});
})