I've combined a few of the other answers into a performance test at https://jsperf.app/lenavi/4:
.match(/\n/g)
from @ngryman and @hashed_name:
(text.match(/\n/g) || '').length + 1
.reduce(...)
from @gil.fernandes:
[...text].reduce((a, c) => a + (c === '\n'), 1)
.split(/\r\n|\r|\n/)
from @Joe, @Pavan, @Aadit M Shah, and @David Hedlund:
text.split(/\r\n|\r|\n/).length
.split(/\n/)
for when you know the line ending, by @jperelli:
text.split(/\n/).length
.split('\n')
which is the same as above, but using a string instead of a regex, by @Krishna Jangid, @jperelli, @Joe, and @Pavan:
text.split('\n').length
Here are the results on my machine with Chrome 123.0.6312.105:
.split('\n')
is the fastest by far.
.split(/\n/)
and .match(/\n/g)
are virtually tied for second at 59% slower.
.split(/\r\n|\r|\n/)
is about 87% slower.
.reduce(...)
is 99% slower. Not even in the same ballpark.
The results are different (on my machine) with Firefox 123.0.1:
.split(/\n/)
and .match(/\n/g)
are virtually tied for first. I'm a little surprised that .split()
did this well. Perhaps the SpiderMonkey JavaScript engine is special-casing this particular call.
.split('\n')
is ~50% slower. I'm very surprised by the difference here between using a one-character string and a one-character regex.
.split(/\r\n|\r|\n/)
is about 66% slower, or 1/3 the speed, which makes sense because it is doing up to 3x the comparisons.
.reduce(...)
is 99% slower (again).
Node uses the same JavaScript engine (V8) as Chrome.
\r\n
. – Depicture