Splitting a string into lines in Javascript
I recently ran into the question of how to split a string into its component lines using Javascript without knowing beforehand what type of linebreaks were being used. After experimenting with the problem for a while, I finally arrived at the following solution (please note that I haven’t tested this cross-browser, but it works great in Safari/WebKit):
var lines = text.match(/^.*([\n\r]+|$)/gm);
Or the alternate version if you want to ensure that each line ends with a single linebreak rather than potentially have lines with multiple line breaks at their end (for my purposes this didn’t matter, but it might for yours):
var lines = text.match(/^.*((\r\n|\n|\r)|$)/gm);
The code assumes that text is a multiline string, and it utilizes the built-in Javascript String.match() method, which when performed with a regex with the global flag enabled will return an array of matches. The multiline flag makes sure that the regex matches at the beginning of every line, and the alternatives at the end of the regex match one or more linebreaks or the end of the line (if we are on the last line). The ultimate result of which is you split the string into a Javascript array with one line per index with the linebreaks preserved.





