Check for lines in textarea with jQuery

I want something like a counter for each line in a text box. This is used when loading a huge number of web banners, so I need a simple counter for the number of users. Right now, the counter only works when the user clicks a link with a special banner.

This is my code as of now:

var i = 0; $('.size').click(function(){ $('#total-number').text(i++); return false; }); 
+7
jquery counter line-breaks
source share
5 answers

Use the String split function ...

 var text = $('#total-number').text(); var eachLine = text.split('\n'); alert('Lines found: ' + eachLine.length); for(var i = 0, l = eachLine.length; i < l; i++) { alert('Line ' + (i+1) + ': ' + eachLine[i]); } 
+4
source share

Using regular expressions, your problem can be solved as follows (search for a text field for the new character of the string "\ n")):

 //assuming $('#total-number') is your textarea element var text = $('#total-number').val(); // look for any "\n" occurences var matches = text.match(/\n/g); // count them, if there are any var breaks = matches ? matches.length : 0; 

breaks Now the variable contains the number of line breaks in the text.

+2
source share

Find the text box for "\ n".

To be sure, search for the regular expression for the pattern "\\ n" and count the array of matches, which will be the number of lines.

0
source share

It works when you mannualy press enter, but is there a way to count line breaks created by textarea when you copy data to it? I mean, if you define the width for the text field and then insert some kind of text, it will create line-by-line ...

0
source share

You mean a single line string that wraps around. A line break, if I am not mistaken, is created by pressing Enter or Shift + Enter.

0
source share

All Articles