How to get the number of lines in a textarea?

Solution 1:

The problem with using "\n" or "\r" is it only counts the number of returns, if you have a line that is long it could wrap and then it wouldn't be counted as a new line. This is an alternative way to get the number of lines - so it may not be the best way.

Edit (thanks alex):

Script

$(document).ready(function(){
 var lht = parseInt($('textarea').css('lineHeight'),10);
 var lines = $('textarea').attr('scrollHeight') / lht;
 console.log(lines);
})

Update: There is a much more thorough answer here: https://stackoverflow.com/a/1761203/145346

Solution 2:

If you are just wanting to test hard line returns, this will work cross platform:

var text = $("#myTextArea").val();   
var lines = text.split(/\r|\r\n|\n/);
var count = lines.length;
console.log(count); // Outputs 4