JSFiddle - React, Tailwind, and code Playground

HTML

<textarea class=text1 id="systemNotesbuilder"  name='systemNotesNew' style='width:100%' rows='15'>Click below line 13 of this textarea and type "a " (letter a then a space).

The text should change to "*Agent [". This works fine.

Now click right below line 11 and type "a "

This works too but the cursor moves to the end of the texarea.

I need it to be placed at the end of the changed text.

Line 11

Line 13
</textarea>

JavaScript

$(function(){   

// capture input

$('#systemNotesbuilder').keyup(function() {
    var currentPosition = this.selectionStart;
 
	//determine line what line number the cursor is on 
    var currentLineNumber= this.value.substr(0, this.selectionStart).split("\n").length;
    
	//get the text of the current line
	var currentLineText = this.value.substr(0, this.selectionStart).split("\n")[currentLineNumber-1];
    
	//split all lines into an array to allow editing
	var arrayOfLines = this.value.split("\n")
    
	//check for "autocorrect" list
	if (currentLineText== "a "){ 
	    arrayOfLines[currentLineNumber-1]= "*Agent [";
        currentPosition += 6; // length of the added text minus linebreak
	} 
	else if (currentLineText.match(/\*Agent \[[\d]{3}/)) {
		arrayOfLines[currentLineNumber-1] =currentLineText.substr(0,9)
	    alert();
    }
	else if (currentLineText.match(/\*Agent \[[\d]{4}/)) {
	
    }
	
	//set contents of the textarea 
	$('#systemNotesbuilder').val(arrayOfLines.join("\n"));
    setSelectionRange(this, currentPosition, currentPosition);

});

});

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}