1

I have a textarea where users can input text.

If the current line starts with 3 spaces and the user hits enter, it will automatically insert 3 spaces and set the cursor right after the spaces. (there may be text before or after)

How can I detect such pattern with JavaScript?

James
  • 2,811
  • 3
  • 25
  • 29

1 Answers1

1

Caret position in textarea, in characters from the start explains how to figure out where the caret is when the user hits enter so that you can check whether there are three spaces and a line break to the left.

Enter key in textarea explains how to detect the Enter key in a textarea and take an action.

Once you have a listener hooked up and know the caret location is caret, you can do something like

if (/(?:^|[\r\n])   (?:[^\r\n ][^\r\n]*)?$/
    .test(myTextArea.value.substring(0, caret)) {
  ...
}

to take an action when there are exactly three spaces at the start of the current line.

To insert the 3 extra-spaces, you could do something like

myTextArea.value = myTextArea.value.substring(0, caret)
    + "\n    " + myTextArea.value.substring(caret);
Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245