[javascript] 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?

This question is related to javascript string split

The answer is


Better solution, as str.split("\n") function creates new array of strings split by "\n" which is heavier than str.match(/\n\g). str.match(/\n\g) creates array of matching elements only. Which is "\n" in our case.

var totalLines = (str.match(/\n/g) || '').length + 1;

To split using a regex use /.../

lines = str.split(/\r\n|\r|\n/); 

I made a performance test comparing split with regex, with a string and doing it with a for loop.

It seems that the for loop is the fastest.

NOTE: this code 'as is' is not useful for windows nor macos endline, but should be ok to compare performance.

Split with string:

split('\n').length;

Split with regex:

split(/\n/).length;

Split using for:

var length = 0;
for(var i = 0; i < sixteen.length; ++i)
  if(sixteen[i] == s)
    length++;

http://jsperf.com/counting-newlines/2


Another short, potentially more performant than split, solution is:

const lines = (str.match(/\n/g) || '').length + 1

Here is the working sample fiddle

Just remove additional \r\n and "|" from your reg ex.


I was testing out the speed of the functions, and I found consistently that this solution that I had written was much faster than matching. We check the new length of the string as compared to the previous length.

const lines = str.length - str.replace(/\n/g, "").length+1;

_x000D_
_x000D_
let str = `Line1
Line2
Line3`;
console.time("LinesTimer")
console.log("Lines: ",str.length - str.replace(/\n/g, "").length+1);
console.timeEnd("LinesTimer")
_x000D_
_x000D_
_x000D_


There are three options:

Using jQuery (download from jQuery website) - jquery.com

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

Using Regex

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

Or, a recreation of a for each loop

var length = 0;
for(var i = 0; i < str.length; ++i){
    if(str[i] == '\n') {
        length++;
    }
}
return length;

 <script type="text/javascript">
      var multilinestr = `
        line 1
        line 2
        line 3
        line 4
        line 5
        line 6`;
      totallines = multilinestr.split("\n");
lines = str.split("\n"); 
console.log(lines.length);
</script>

thats works in my case


Hmm yeah... what you're doing is absolutely wrong. When you say str.split("\r\n|\r|\n") it will try to find the exact string "\r\n|\r|\n". That's where you're wrong. There's no such occurance in the whole string. What you really want is what David Hedlund suggested:

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

The reason is that the split method doesn't convert strings into regular expressions in JavaScript. If you want to use a regexp, use a regexp.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to split

Parameter "stratify" from method "train_test_split" (scikit Learn) Pandas split DataFrame by column value How to split large text file in windows? Attribute Error: 'list' object has no attribute 'split' Split function in oracle to comma separated values with automatic sequence How would I get everything before a : in a string Python Split String by delimiter position using oracle SQL JavaScript split String with white space Split a String into an array in Swift? Split pandas dataframe in two if it has more than 10 rows