如何获得textarea中的行数?

时间:2022-06-21 15:10:18

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

我想要的是计算textarea中的行数,例如:

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

最多可以计4行。基本上按一次输入会转移到下一行

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.

无论有多少行,它总是给出'1'。

11 个解决方案

#1


16  

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

我已经将lines和lineCount方法实现为String原型:

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.

显然,split方法不会在IE9的字符串末尾(或textarea的innerText属性)中计算回车符和/或换行符,但它会在Chrome 22中计算它,产生不同的结果。

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

到目前为止,我通过在浏览器不是Internet Explorer时从行数中减去1来适应这种情况:

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

Hopefully someone has a better RegExp or another workaround.

希望有人有更好的RegExp或其他解决方法。

#2


38  

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.

使用“\ n”或“\ r \ n”的问题是它只计算返回的数量,如果你有一个很长的行可以换行,那么它就不会被计算为新行。这是获得行数的另一种方法 - 因此它可能不是最佳方式。

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://*.com/a/1761203/145346

更新:这里有一个更彻底的答案:https://*.com/a/1761203/145346

#3


22  

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

#4


8  

user \n instead of \r

user \ n而不是\ r \ n

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

#5


2  

What about splitting on "\n" instead?

那么拆分“\ n”呢?

It will also be a problem where one line wrapped to 2 lines in the textarea.

这也是一个问题,其中一行包裹在textarea中的2行。

To do it accurately like this, you could use a fixed height font and measure pixels. This could be problematic though.

要像这样准确地执行此操作,您可以使用固定高度字体并测量像素。但这可能会有问题。

#6


2  

This function counts the number of lines which have text in a textarea:

此函数计算textarea中包含文本的行数:

function countLine(element) {
  var text = $(element).val();
  var lines = text.split("\n");
  var count = 0;
  for (var i = 0; i < lines.length-1; i++) {
    if (lines[i].trim()!="" && lines[i].trim()!=null) {
      count += 1;
    }
  }
  return count;
}

#7


1  

The normal newline character is "\n". The convention on some systems is to also have "\r" beforehand, so on these systems "\r\n" is often found to mean a new line. In a browser, unless the user intentionally enters a "\r" by copying it from somewhere else, the newline will probably be expressed as just "\n". In either case splitting by "\n" will count the number of lines.

普通的换行符是“\ n”。某些系统的惯例是事先也有“\ r”,所以在这些系统中,“\ r \ n”经常被认为是一个新的线。在浏览器中,除非用户通过从其他地方复制它而故意输入“\ r”,否则换行符可能只表示为“\ n”。在任何一种情况下,按“\ n”分割将计算行数。

#8


1  

I've used the original answer of Mottie but some functions were changed in the JQuery API. Here is the working function for the current API v3.1.0:

我使用了Mottie的原始答案,但是在JQuery API中更改了一些函数。以下是当前API v3.1.0的工作函数:

var lht = parseInt($('#textarea').css('lineHeight'),10);
    var lines = $('#textarea').prop('scrollHeight') / lht;
    console.log(lines);

All tumbs up for Mottie's answer!

所有人都为Mottie的答案而烦恼!

#9


0  

<html>
<head>
<script>
function countLines(theArea){
var theLines = theArea.value.replace((new RegExp(".{"+theArea.cols+"}","g")),"\n").split("\n");
if(theLines[theLines.length-1]=="") theLines.length--;
theArea.form.lineCount.value = theLines.length;
}
</script>
</head>
<body>
<form>
<textarea name="myText" onKeyUp="countLines(this)" cols="10" rows="10">
</textarea>
<br>
Lines:
<input type=text name="lineCount" size="2" value="0">
</form>
</body>
</html>

#10


0  

However this is working if you need use it because it respond to your problem

但是,如果您需要使用它,这是有效的,因为它可以解决您的问题

let text = document.getElementById("myTextarea").value;   
let lines = text.split(/\r|\r\n|\n/);
let count = lines.length;
console.log(count);

#11


0  

Your ans can be done in very simple way.

你的ans可以用非常简单的方式完成。

var text = $("#myTextArea").val();

               // will remove the blank lines from the text-area
                text = text.replace(/^\s*[\r\n]/gm, "");

               //It will split when new lines enter
                var lines = text.split(/\r|\r\n|\n/);

             var count = lines.length; //now you can count thses lines.
                console.log(count);

This code for exact lines filled in the textarea. and will work for sure.

此代码用于填写textarea中的确切行。并肯定会工作。

#1


16  

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

我已经将lines和lineCount方法实现为String原型:

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.

显然,split方法不会在IE9的字符串末尾(或textarea的innerText属性)中计算回车符和/或换行符,但它会在Chrome 22中计算它,产生不同的结果。

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

到目前为止,我通过在浏览器不是Internet Explorer时从行数中减去1来适应这种情况:

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

Hopefully someone has a better RegExp or another workaround.

希望有人有更好的RegExp或其他解决方法。

#2


38  

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.

使用“\ n”或“\ r \ n”的问题是它只计算返回的数量,如果你有一个很长的行可以换行,那么它就不会被计算为新行。这是获得行数的另一种方法 - 因此它可能不是最佳方式。

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://*.com/a/1761203/145346

更新:这里有一个更彻底的答案:https://*.com/a/1761203/145346

#3


22  

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

#4


8  

user \n instead of \r

user \ n而不是\ r \ n

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

#5


2  

What about splitting on "\n" instead?

那么拆分“\ n”呢?

It will also be a problem where one line wrapped to 2 lines in the textarea.

这也是一个问题,其中一行包裹在textarea中的2行。

To do it accurately like this, you could use a fixed height font and measure pixels. This could be problematic though.

要像这样准确地执行此操作,您可以使用固定高度字体并测量像素。但这可能会有问题。

#6


2  

This function counts the number of lines which have text in a textarea:

此函数计算textarea中包含文本的行数:

function countLine(element) {
  var text = $(element).val();
  var lines = text.split("\n");
  var count = 0;
  for (var i = 0; i < lines.length-1; i++) {
    if (lines[i].trim()!="" && lines[i].trim()!=null) {
      count += 1;
    }
  }
  return count;
}

#7


1  

The normal newline character is "\n". The convention on some systems is to also have "\r" beforehand, so on these systems "\r\n" is often found to mean a new line. In a browser, unless the user intentionally enters a "\r" by copying it from somewhere else, the newline will probably be expressed as just "\n". In either case splitting by "\n" will count the number of lines.

普通的换行符是“\ n”。某些系统的惯例是事先也有“\ r”,所以在这些系统中,“\ r \ n”经常被认为是一个新的线。在浏览器中,除非用户通过从其他地方复制它而故意输入“\ r”,否则换行符可能只表示为“\ n”。在任何一种情况下,按“\ n”分割将计算行数。

#8


1  

I've used the original answer of Mottie but some functions were changed in the JQuery API. Here is the working function for the current API v3.1.0:

我使用了Mottie的原始答案,但是在JQuery API中更改了一些函数。以下是当前API v3.1.0的工作函数:

var lht = parseInt($('#textarea').css('lineHeight'),10);
    var lines = $('#textarea').prop('scrollHeight') / lht;
    console.log(lines);

All tumbs up for Mottie's answer!

所有人都为Mottie的答案而烦恼!

#9


0  

<html>
<head>
<script>
function countLines(theArea){
var theLines = theArea.value.replace((new RegExp(".{"+theArea.cols+"}","g")),"\n").split("\n");
if(theLines[theLines.length-1]=="") theLines.length--;
theArea.form.lineCount.value = theLines.length;
}
</script>
</head>
<body>
<form>
<textarea name="myText" onKeyUp="countLines(this)" cols="10" rows="10">
</textarea>
<br>
Lines:
<input type=text name="lineCount" size="2" value="0">
</form>
</body>
</html>

#10


0  

However this is working if you need use it because it respond to your problem

但是,如果您需要使用它,这是有效的,因为它可以解决您的问题

let text = document.getElementById("myTextarea").value;   
let lines = text.split(/\r|\r\n|\n/);
let count = lines.length;
console.log(count);

#11


0  

Your ans can be done in very simple way.

你的ans可以用非常简单的方式完成。

var text = $("#myTextArea").val();

               // will remove the blank lines from the text-area
                text = text.replace(/^\s*[\r\n]/gm, "");

               //It will split when new lines enter
                var lines = text.split(/\r|\r\n|\n/);

             var count = lines.length; //now you can count thses lines.
                console.log(count);

This code for exact lines filled in the textarea. and will work for sure.

此代码用于填写textarea中的确切行。并肯定会工作。