How to count the number of lines of a string in 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/
Another short, potentially more performant than split, solution is:
const lines = (str.match(/\n/g) || '').length + 1
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.