How to get the number of lines in a 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

should count up to 4 lines. Basically pressing 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.

Answers:

Answer

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
Answer

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

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

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.

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

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>

Answer

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.

Answer

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

Answer

user \n instead of \r

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

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.

Answer

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!

Answer

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.

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

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
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.