开发者

How to get the number of lines in a textarea?

开发者 https://www.devze.com 2022-12-16 02:29 出处:网络
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 press开发者_StackOverflow中文版ing enter once would transfer

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 press开发者_StackOverflow中文版ing 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.


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.

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


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


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.


user \n instead of \r

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


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


What about splitting on "\n" instead?

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

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


This function counts the number of lines which have text in a 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;
}


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:

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

All tumbs up for Mottie's answer!


This will aim to consider lines with both hard and soft returns:

    //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(/\r|\r\n|\n/);
    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));


Counting the newlines is not a reliable way for finding the number of lines, since long text could simply break and still only count as a single line. What you want to do, is find out the scrollHeight of the textarea and divide it by the height of a single line.

This is answered in detail here: https://stackoverflow.com/a/1761203/9863305


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.


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


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*[\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.


Instead of textarea you could use a div with the attribute contenteditable="true". On a div with this attribute you can write anything, just like in a textarea, but any new line (except the first) is automatically wrapped inside a div. You can use jQuery or JS to count the div's and add +1, which is the first line.

It's a no brainer, i would use this instead of textarea with every occasion. It has several advantages. It auto resizes, you can easily count blank lines, you can customize every div or add spans with colors or font sizes or anything, you can use any line-height and any font-size, you can add rich text features and more, it's better for SEO and more. Here is a working example with jQuery:

    $("#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>


Try calling this function every time you change its value.

 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 '\n'. 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] == '\n') {
      count++
    }
  }
  console.log(count)

In this live demonstration we can see a concrete case with 3 sentences :

const textareaLineCount = () => {
  let count = 0
  const a = document.querySelector('textarea')
  for (let i = 0; i < a.value.length; i++) {
    if (a.value[i] == '\n') {
      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>

⚠️ It's possible that the last phase is not a line break, so I advise you to add 1 to the total result

0

精彩评论

暂无评论...
验证码 换一张
取 消