Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  35] [ 4]  / answers: 1 / hits: 123484  / 15 Years ago, sun, january 10, 2010, 12:00:00

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.


More From » jquery

 Answers
89

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.


[#97880] Wednesday, January 6, 2010, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;