English 中文(简体)
• 如何在文本中获取线数?
原标题:How to get the number of lines in a textarea?

我想在案文中计算线数,例如:

line 1
line 2
line 3
line 4

最多可计算4行。 基本上迫切需要一劳永逸地把你转到下行。

The following Code isn t working:

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

它总是给予1条,不管有多少条线。

最佳回答

我已采用了强硬原型的线和线性方法:

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

很显然,分离的方法不会在IE9的护法(或正文区内部财产)结束时算出运输回报和(或)新的线性,但会将其算作 Chrome22,产生不同的结果。

到目前为止,在浏览器不是因特网探索者的情况下,我已经通过从线数中分出1个字句来达到这一目的。

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

希望有人能有更好的补习或另一种工作。

问题回答

The problem with using " " or " " 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.

Edit (thanks alex):

原文

$(document).ready(function(){
 var lht = parseInt($( textarea ).css( lineHeight ),10);
 var lines = $( textarea ).attr( scrollHeight ) / lht;
 console.log(lines);
})

最新资料:

如果你只是想测试硬线回归,这将跨平台:

var text = $("#myTextArea").val();   
var lines = text.split(/
|
|
/);
var count = lines.length;
console.log(count); // Outputs 4

user instead of

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

然而,如果你需要使用这一工具,是因为你回答了你的问题,那么这项工作是有效的。

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

What about splitting on " " instead?

还有一个问题,在案文中,一行划为两行。

为了准确做到这一点,你可以使用固定的高温线和测量假象。 这可能是个问题。

该职能包括文本中文本的行文数量:

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

我先用了Mointtie的原始答案,但在JQuery AP中,一些功能发生了变化。 本文是目前APIC/L.01号文件的工作职能:

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

All tumb up for Mottie s response!

目的是考虑硬性和软性回归的界线:

    //determine what the fontsize will be
    let fontsize = 12;
    //get number of characters that can fit in a row
    let charsperrow = textarea.clientWidth / fontsize;
    //get any hard returns
    let hardreturns = textarea.textContent.split(/
|
|
/);
    let rows = hardreturns.length;
    //loop through returns and calculate soft returns
    for(let i = 0,len = rows; i < len; i++){
        let line = hardreturns[i];
        let softreturns = Math.round(line.length / charsperrow);
        //if softreturns is greater than 0, minus by 1 (hard return already counted)
        softreturns = Math.round(softreturns > 0 ? (softreturns - 1) : 0);
        rows += softreturns;
    }
    console.log(Math.round(rows));

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

<html>
<head>
<script>
function countLines(theArea){
var theLines = theArea.value.replace((new RegExp(".{"+theArea.cols+"}","g")),"
").split("
");
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>

Your ans can be done in very simple way.

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

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

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

             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.

您可以使用“属性”(contenteditable="true”()的四分之四。 在一定程度上,你可以写任何东西,就像在文本中那样,但任何新行(除第1条外)都自动在内包装。 您可使用jQuery或JS,计算div和添加+1,这是第一条。

它没有大脑,即每次使用<条码>。 它有若干优势。 自动裁量,你可以轻松地计算空白线,你可以定制每一条线,或增加有色体或字体大小的距离,你可以使用任何<条码>-八条<>和任何<条码>。 这里是一个与 j合的榜样:

    $("#Editor").on("keyup mouseup", function(){
        blankSpace = $(this).find("br").length; //count blank lines
        urlCounter = $(this).find("div").length + 1 - blankSpace;

        $(".lineCounter").text("Number of links: "+ urlCounter);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Editor" contenteditable="true" style="color:aqua;width: 100%;height: 100%;background: blue;"></div>
<div class="lineCounter" style="position: absolute;bottom: 0;z-index: 999;left: 0;"></div>

每当你改变其价值时,要求履行这一职能。

 textArea.addEventListener( input , function() {
        setDynamicHeight();
 });

 function setDynamicHeight() {
    textArea.style.height = 0; // set the height to 0 in case of it has to be shrinked
    textArea.style.height = textArea.scrollHeight +  px ; // set the dynamic height
}

Each line break is defined by . The goal is to count them. For this, we will have to iterate on this with a loop on each character. See the example below

  let count = 0
  const a = document.querySelector( textarea )
  for (let i = 0; i < a.value.length; i++) {
    if (a.value[i] ==  
 ) {
      count++
    }
  }
  console.log(count)

在这种活生的示威中,我们可以看到一个具体案例,有3句:

const textareaLineCount = () => {
  let count = 0
  const a = document.querySelector( textarea )
  for (let i = 0; i < a.value.length; i++) {
    if (a.value[i] ==  
 ) {
      count++
    }
  }
  return count
}

const displayTotalTextareaLine = (total) => {
  document.querySelector( p ).innerText = total
}

document.querySelector( button ).addEventListener( click , () => {
  const total = textareaLineCount()
  displayTotalTextareaLine(total)
})
<textarea>
  Lorem ipsum dolor sit amet.
  Lorem ipsum dolor sit amet.
  Lorem ipsum dolor sit amet.
</textarea>
<button>count</button>
<p></p>

<>0> 最后一个阶段可能不是一线中断,因此我建议你在总结果中增加1个。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签