Skip to content
Advertisement

How to get the number of lines in a textarea?

What I would like is to count the number of lines in a textarea, e.g:

line 1
line 2
line 3
line 4

should count up to 4 lines. Basically pressing enter once would transfer you to the next line

The following code isn’t working:

var text = $("#myTextArea").val();   
var lines = text.split("r");
var count = lines.length;
console.log(count);

It always gives ‘1’ no matter how many lines.

Advertisement

Answer

I have implemented the lines and lineCount methods as String prototypes:

String.prototype.lines = function() { return this.split(/r*n/); }
String.prototype.lineCount = function() { return this.lines().length; }

Apparently the split method will not count a carriage return and/or newline character at the end of the string (or the innerText property of a textarea) in IE9, but it will count it in Chrome 22, yielding different results.

So far I have accomodated for this by subtracting 1 from the line count when the browser is other than Internet Explorer:

String.prototype.lineCount = function() { return this.lines().length - navigator.userAgent.indexOf("MSIE") != -1); }

Hopefully someone has a better RegExp or another workaround.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement