如何在 javascript 中计算字符串的行数

我想计算一个字符串中的行数,

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

在这个字符串上(最初是一个缓冲区) :

 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

出于某种原因,我得到了 lines='1'

有什么办法吗?

142547 次浏览

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/

Here is the working sample fiddle

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

To split using a regex use /.../

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

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.

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;

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

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

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;

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

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