How to detect line breaks in a text area input?

You can use match on the string containing the line breaks, and the number of elements in that array should correspond to the number of line breaks.

enteredText = textareaVariableName.val();
numberOfLineBreaks = (enteredText.match(/\n/g)||[]).length;
characterCount = enteredText.length + numberOfLineBreaks;

/\n/g is a regular expression meaning ‘look for the character \n (line break), and do it globally (across the whole string).

The ||[] part is just in case there are no line breaks. Match will return null, so we test the length of an empty array instead to avoid errors.

Leave a Comment