Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of lines of a string in javascript

I want to count the number of lines in a string

i tried to use this stackoverflow answer :

lines = str.split("\r\n|\r|\n");  return  lines.length; 

on this string(which was originally a buffer):

 GET / HTTP/1.1  Host: localhost:8888  Connection: keep-alive  Cache-Control: max-age=0  User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.2 (KHTML,like Gecko) Chrome/15.0.874.121 Safari/535.2  Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  Accept-Encoding: gzip,deflate,sdch  Accept-Language: en-US,en;q=0.8  Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 

and for some reason i got lines='1'.

any idea how to make it work?

like image 801
Itzik984 Avatar asked Dec 13 '11 11:12

Itzik984


People also ask

How do I count strings in JavaScript?

In JavaScript, we can count the string occurrence in a string by counting the number of times the string present in the string. JavaScript provides a function match(), which is used to generate all the occurrences of a string in an array.

How do I count the number of lines in a div?

Divide the Element's Height by its Line Height To get the number of lines in an element, we can divide the element's height by its line-height. Then we can do the computation by writing: const el = document. querySelector('div'); const divHeight = +el.

How do you count the number of lines in a text area?

To get the number of lines in a textarea using JavaScript, we can call split on the input value of the textarea by the newline character. Then we get the length of the returned string array.


1 Answers

Using a regular expression you can count the number of lines as

 str.split(/\r\n|\r|\n/).length 

Alternately you can try split method as below.

var lines = $("#ptest").val().split("\n");   alert(lines.length); 

working solution: http://jsfiddle.net/C8CaX/

like image 129
Pavan Avatar answered Sep 30 '22 18:09

Pavan