Insert text on last cursor position

Sometimes, I wanna implement the Editor application which has to insert the text system.
So If it has like a below text on textarea, it will be able to insert text on the last cursor position when something action.

# Here is title
This is a markdown textarea.

I wanna insert new text on last cursor.

In this case, I’ll insert a link text.


You can implement with JavaScript.

const insertText = () => {
    const element = document.querySelector('textarea');
    const word = 'your original text';
    const sentence = element.value;
    const len = sentence.length;
    const pos = element.selectionStart;
    const before = sentence.substr(0, pos);
    const after = sentence.substr(pos, len);
    const newText = before + word + after;
    element.value = newText;
  1. You have to get target element DOM
  2. Create original text
  3. Get an all text on target element(textarea)
  4. Get all text string length
  5. Then, textarea last cursor position(selectionStart is last cursor position length which includes number)
  6. Get text after and before selectionStart
  7. Finally, create new text and insert target element