如何获得textarea中的行数? [英] How to get the number of lines in a textarea?
问题描述
我想要的是计算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
最多可计入4行。基本上按一次输入会转移到下一行
should count up to 4 lines. Basically pressing enter once would transfer you to the next line
以下代码不起作用:
var text = $("#myTextArea").val();
var lines = text.split("\r");
var count = lines.length;
console.log(count);
无论有多少行,它总是给出'1'。
It always gives '1' no matter how many lines.
推荐答案
我已经将line和lineCount方法实现为String原型:
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; }
显然,split方法不会计算结尾处的回车符和/或换行符。 IE9中的字符串(或textarea的innerText属性),但它会在Chrome 22中计算它,产生不同的结果。
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.
到目前为止,我通过减去它来适应这一点当浏览器不是Internet Explorer时,行数为1:
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); }
希望有人有更好的RegExp或其他解决方法。
Hopefully someone has a better RegExp or another workaround.
这篇关于如何获得textarea中的行数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!