How to insert a text where cursor is using JavaScript?

Sometimes, we want to insert a text where cursor is using JavaScript.

In this article, we’ll look at how to insert a text where cursor is using JavaScript.

How to insert a text where cursor is using JavaScript?

To insert a text where cursor is using JavaScript, we can get the caret position with the selectionStart property of the element.

For instance, we write

const insertAtCaret = (el, text) => {
  const caretPos = el.selectionStart;
  const textAreaTxt = el.value;
  el.value =
    textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos);
};

to create the insertAtCaret function.

In it, we get the cursor position with el.selectionStart.

And then we get the input value with el.value.

Then we set new text box value with

textAreaTxt.substring(0, caretPos) + text + textAreaTxt.substring(caretPos)

To put the text where the cursor is.

Conclusion

To insert a text where cursor is using JavaScript, we can get the caret position with the selectionStart property of the element.