Javascript 如何获取textarea中的行数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2035910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:30:13  来源:igfitidea点击:

How to get the number of lines in a textarea?

javascriptjquery

提问by Click Upvote

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”。

采纳答案by hector-j-rivas

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 或其他解决方法。

回答by Mottie

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" 的问题是它只计算返回的数量,如果你有一个很长的行,它可以换行,然后它就不会被算作一个新行。这是获取行数的另一种方法 - 所以它可能不是最好的方法。

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

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

回答by Doug Neiner

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

回答by Marek Karbarz

user \ninstead of \r

用户\n而不是\r

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

回答by Ir Calif

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);

回答by Tran Duy

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;
}

回答by alex

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.

要像这样准确地做到这一点,您可以使用固定高度的字体并测量像素。但这可能有问题。

回答by Quispie

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!

所有的人都为莫蒂的回答加油!

回答by humo

<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>

回答by Danny Roberts

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" 拆分都会计算行数。