How to count the number of lines of a string in javascript
JavascriptStringSplitJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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/
Solution 2 - Javascript
Another short, potentially more performant than split, solution is:
const lines = (str.match(/\n/g) || '').length + 1
Solution 3 - Javascript
To split using a regex use /.../
lines = str.split(/\r\n|\r|\n/);
Solution 4 - Javascript
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.
Solution 5 - Javascript
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++;
Solution 6 - Javascript
There are three options:
Using jQuery (download from http://www.jquery.com">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;
Solution 7 - Javascript
Another solution for this problem using the spread operator and no regular expressions would be:
const lines = [...csv].reduce((a, c) => a + (c === '\n' ? 1 : 0), 0)
const csv = `
demo_budget_2021_v4_wk_9,test,Civil,Spares,test,false,12,2021,100
demo_budget_2021_v4_wk_9,test,Civil,Spares,test,false,11,2021,100
demo_budget_2021_v4_wk_9,test,Civil,Spares,test,false,10,2021,100
demo_budget_2021_v4_wk_9,test,Civil,Spares,test,false,9,2021,100
`
const lines = [...csv].reduce((a, c) => a + (c === '\n' ? 1 : 0), 0)
console.log(lines);
Solution 8 - Javascript
Here is the working sample fiddle
Just remove additional \r\n and "|" from your reg ex.
Solution 9 - Javascript
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;
Solution 10 - Javascript
<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
Solution 11 - Javascript
I was testing out the speed of the functions, and I found consistently that this solution that I had written was much faster than match
ing. We check the new length of the string as compared to the previous length.
const lines = str.length - str.replace(/\n/g, "").length+1;
let str = `Line1
Line2
Line3`;
console.time("LinesTimer")
console.log("Lines: ",str.length - str.replace(/\n/g, "").length+1);
console.timeEnd("LinesTimer")